【问题标题】:kivy adding variables to the root widgetkivy 将变量添加到根小部件
【发布时间】:2014-11-25 03:53:59
【问题描述】:

我想制作一个 kivy 程序,它从文本输入中获取一个数字,将数字加一并写入标签。

但程序不接受我的变量作为根小部件的一部分。

这是程序:

import kivy
from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import *
from kivy.graphics.vertex_instructions import *
from kivy.graphics.context_instructions import *

kivy.lang.Builder.load_string('''
<my_layout>:
    orientation: 'vertical'
    canvas:
        Color
            rgba: 10, 10, 0, 1
    Label:
        id: label0
        text: 'Wie viel Wiegt das Ei in gramm?'
        font_size: 50


    TextInput:
        id: my_textinput
        font_size: 100
        size_hint_y: None
        height: 100
    Button:
        id: my_button
        height: 100
        text: 'button'
        canvas:
            Color:
                rgba: 0, 0, 20, 1
        on_press: root.berechnen(my_textinput.text)
    Label:
        id: label1
        text: root.var
''')

class my_layout(BoxLayout):
    def __init__(self, **kwargs):
        super(my_layout,self).__init__(**kwargs)
        self.var = self.number
    def berechnen(self, txt):
        self.number = txt

class Add(App):
    def build(self):
        return my_layout()

if __name__ == "__main__":
    Add().run()

【问题讨论】:

    标签: python oop kivy


    【解决方案1】:

    您设置了 self.var,但这不是 kivy 属性,因此 gui 不知道它已更改并且不设置该属性。

    你可以这样做

    from kivy.properties import StringProperty
    
    class my_layout(BoxLayout):
        var = StringProperty('')
    

    否则继续相同的操作。

    看起来您的代码也会崩溃,因为您没有设置self.number,但您确实引用了它。也许这是粘贴示例时的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多