【问题标题】:Kivy object doesn't render when defined in .kv fileKivy 对象在 .kv 文件中定义时不呈现
【发布时间】:2016-10-14 13:14:07
【问题描述】:

我正在用 kivy 开发一个应用程序,目前正试图弄清楚为什么当我在 Python 中而不是在 .kv 文件中添加对象时,我可以得到一个要渲染的对象。

这很好用,渲染背景图像,上面有一个开关。

class LoginScreen(Screen):
    def __init__(self,**kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.layout = BoxLayout(orientation='vertical')
        self.add_widget(self.layout)
        self.layout.add_widget(defSwitch())
    def on_touch_up(self,touch):
        if self.collide_point(*touch.pos):
            self.parent.current = 'data'

class defSwitch(Switch):
    active = False

.kv 文件在哪里:

<LoginScreen>:
    imgname: './images/' + 'login.jpg'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: self.imgname

除了背景图像之外什么都不渲染:

class LoginScreen(Screen):
    def on_touch_up(self,touch):
        if self.collide_point(*touch.pos):
            self.parent.current = 'data'

class defSwitch(Switch):
    active = False

在这种情况下 .kv 文件的位置:

<LoginScreen>:
    imgname: './images/' + 'login.jpg'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: self.imgname
    BoxLayout:
        orientation: 'vertical'
        defSwitch:

如果我将 .kv 文件中的 defSwitch: 替换为默认的 Switch 对象,则它可以正常渲染。为什么我不能使用自定义对象?

【问题讨论】:

    标签: python python-2.7 kivy python-2.x kivy-language


    【解决方案1】:

    如果你想使用kv语言在.py文件中创建的自定义类,你也需要在.kv文件中设置它:

    <defScreen>:    # class def
    
    <LoginScreen>:
        ...
        defScreen:  # object
    

    这样它就知道要寻找什么。

    另外,我想建议您在 kv 语言中使用驼峰式大小写,因为在 situations 中,解析器不会将短语识别为小部件。

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      相关资源
      最近更新 更多