Kivy - 标签文本没有改变

Kivy - Label text is not changing

我的第一个问题 :),对你们来说可能是一个简单的问题... 我在按下按钮时遇到标签文本更改问题。

代码如下。 我尝试了 on_press 定义的多种变体:

self.on_press=lambda:YellowLabel.change_text(YellowLabel)
self.on_press=lambda:YellowLabel.change_text

无效

self.on_press=YellowLabel.change_text(YellowLabel)

returns:

KeyError: 'text'

我猜这可能是由于冲突,因为在Label初始化之前调用了函数。当我尝试

self.on_press=YellowLabel.change_text

它returns:

TypeError: change_text() missing 1 required positional argument: 'self'

我也试过很多其他的变体,但我就是做不到。 并且,change_text 中的打印功能在下面的示例中有效,但标签文本没有改变。 我也曾尝试将 change_text 放在 YellowLabel class 之外,但仍然没有成功...

我做错了什么? 现在,我在想也许 change_text 功能不好,但我不明白为什么...

p.s。我确实在这个网站上浏览了许多与 kivy 相关的问题,并尝试了它们,但我就是无法让它工作。

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class RedButton(Button):
    def __init__(self,txt="RED LABEL",**kwargs):
        super(RedButton,self).__init__(txt="RED LABEL",**kwargs)
        self.text=(txt)
        self.color=[1,0,0,1]
        self.on_press=lambda:YellowLabel.change_text(YellowLabel)


class YellowLabel(Label):
    def __init__(self,**kwargs):
        super(YellowLabel,self).__init__(**kwargs)
        self.text=("yellow")
        self.color=[1,1,0,1]
        self.id="yelb"

    def change_text(self):
        print("printed")
        self.text=("new yellow text")   

class Window(BoxLayout):
    def __init__(self,**kwargs):
        super(Window,self).__init__(orientation="vertical",**kwargs)
        self.add_widget(RedButton(txt="new red button"))
        self.add_widget(YellowLabel())

class UpdateApp(App):
    def build(self):
        return Window()

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

我想说问题可能在于 self.on_press=lambda:YellowLabel.change_text(YellowLabel) 您缺少对在 Window __init__ 中创建的 YellowLable 的引用。您应该尝试从 Window 对象获取 YellowLable 小部件并在该

上调用 change_text()

你的评论代码(毕竟你自己弄明白了:-)):

class Window(BoxLayout):
        def __init__(self,**kwargs):
            super(Window,self).__init__(orientation="vertical",**kwargs)
            rb=RedButton(txt="new red button")
            self.add_widget(rb)
            yl=YellowLabel()
            self.add_widget(yl)
            rb.on_press=lambda:YellowLabel.change_text(yl)