Kivy如何在不同的屏幕上更改StringProperty值?

2024-03-28 15:40:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序从数据库中获取数据,并存储在Python中的变量中。下面的代码是一个简化版本,其中有两个屏幕。第一个屏幕有两个按钮,第二个屏幕有一个标签和一个后退按钮。第二个屏幕上的标签文本将根据按下的按钮而改变。在

运行时,标签设置为StringProperty的值,即“Test”。当单击其中一个按钮时,ChangeScreen函数将运行并计算出正确的新标签。第二个函数上的LabelUpdater函数已运行,它应该更改字符串属性,但没有更改。如何解决此问题?谢谢<;3

Python:

import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty

class DemoScreen1(Screen):
    def ChangeScreen(self, button_text):
        if button_text == "Button 1":
            new_label = "This is the new label when button 1 is pressed"
            DemoScreen2.LabelUpdater(new_label)
        else:
            new_label2 = "This is the new label when button 2 is pressed"
            DemoScreen2.LabelUpdater(new_label2)
        self.parent.current = "demoscreen2"

class DemoScreen2(Screen):
    screen2_label = StringProperty("Test")
    def LabelUpdater(NEW_LABEL):
        screen2_label = StringProperty(NEW_LABEL)

class AppScreenManager(ScreenManager):
    pass
class Tester(App): 
    pass
if __name__ == '__main__':
    Tester().run() 

基维:

^{pr2}$

Tags: 函数fromimportnew屏幕isbutton标签
1条回答
网友
1楼 · 发布于 2024-03-28 15:40:21

使用ids并通过AppScreenManager即屏幕管理器进行引用。在

self.parent.ids.screen2.screen2_label = new_label

请参阅下面的完整示例。在

^{pr2}$

千伏

AppScreenManager:
    DemoScreen1:
        id: screen1
    DemoScreen2:
        id: screen2

<DemoScreen1>:
    name: "demoscreen1"
    orientation: "vertical"
    GridLayout:
        rows: 2
        Button:
            id: Button1
            text: "Button 1"
            on_release: root.ChangeScreen(Button1.text)
        Button:
            id: Button2
            text: "Button 2"
            on_release: root.ChangeScreen(Button2.text)

<DemoScreen2>:
    name: "demoscreen2"
    orientation: "vertical"
    GridLayout:
        rows:2
        Label:
            text: root.screen2_label
        Button:
            text:"Back"
            on_release: app.root.current = "demoscreen1"

相关问题 更多 >