gpt4 book ai didi

python - 在kivy中使用python将变量从一个屏幕更改为另一个屏幕

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:48 24 4
gpt4 key购买 nike

我有一个双屏 kivy 应用程序,我想使用 python 将变量从一个屏幕传递到第二个屏幕。

Python文件

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty,ObjectProperty
from kivy.uix.label import Label

class MenuScreen(Screen):
label1=StringProperty()
label2=StringProperty()
def __init__(self,**kwargs):
super(MenuScreen, self).__init__(**kwargs)
self.label1="hello"
self.label2="world"
def change_text(self):
lbl1=self.label1+ " and "
lbl2= "A beautiful "+self.label2
chg=SettingsScreen()
chg.UpdateSettings(lbl1,lbl2)

# HERE: something like



class SettingsScreen(Screen):
label3=StringProperty()
label4=StringProperty()
def __init__(self,**kwargs):
super(SettingsScreen, self).__init__(**kwargs)
#some default texts
self.label3="Nothing"
self.label4="Nothing"
def UpdateSettings(self,lbl1,lbl2):
print(lbl1,lbl2)
self.label3=lbl1
self.label4=lbl2

class TestScreenManager(ScreenManager):
menu_screen=ObjectProperty(None)
settings_screen=ObjectProperty(None)

class TestApp(App):
def build(self):
return TestScreenManager()

TestApp().run()

kv文件

#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#: import SettingsScreen screen


<TestScreenManager>:
id: screen_manager
menu_screen: menu_screen
settings_screen: settings_screen

MenuScreen:
id: menu_screen
name: 'menu'
manager: screen_manager
SettingsScreen:
id: settings_screen
name: 'settings_screen'
manager: screen_manager


<MenuScreen>:
name: 'MenuScreen'
BoxLayout:
Label:
text:root.label1
Label:
text:root.label2
Button:
text: 'Goto nn'
size_hint_y:0.2
on_press:
root.manager.current = 'settings_screen'
root.change_text()


<SettingsScreen>:
#name: 'SettingsScreen'
label_id: label_field
BoxLayout:
Label:
text:root.label3
Label:
text:root.label4
Label:
id: label_field
text: "some text"

它运行时没有错误,但它没有更改第二个屏幕的变量。为了调试,我在 UpdateSetting 函数中添加了 print(lbl1,lbl2) ,它打印出传递的 lbl1 和 lbl2 变量,但它不更新标签。

最佳答案

当您执行 chg=SettingsScreen() 时,您将创建 SettingsScreen 类的新实例,并修改该实例的标签实例。您需要访问 ScreenManager 使用的对象,而不是创建一个新对象。

您可以使用当前屏幕的manager属性来获取另一个屏幕的实例引用:

def change_text(self):          
lbl1=self.label1 + " and "
lbl2= "A beautiful "+ self.label2
chg = self.manager.settings_screen #<<<<<<<<<<<<<<
chg.UpdateSettings(lbl1,lbl2)

关于python - 在kivy中使用python将变量从一个屏幕更改为另一个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com