Python 需要将变量传递到新屏幕,然后读取并使用它
如何使用Kivy和Python根据我按下的按钮更改第二个屏幕的颜色/图像?下面是说明我的问题的代码 Python:Python 需要将变量传递到新屏幕,然后读取并使用它,python,python-3.x,kivy,kivy-language,Python,Python 3.x,Kivy,Kivy Language,如何使用Kivy和Python根据我按下的按钮更改第二个屏幕的颜色/图像?下面是说明我的问题的代码 Python: startvalue = 0 class Start(Screen): pass class End(Screen): global startvalue def which_color(self): if startvalue == 1: self.bg_image.source = 'blue.png'
startvalue = 0
class Start(Screen):
pass
class End(Screen):
global startvalue
def which_color(self):
if startvalue == 1:
self.bg_image.source = 'blue.png'
elif startvalue == 2:
self.bg_image.source = 'red.png'
elif startvalue == 3:
self.bg_image.source = 'yellow.jpg'
elif startvalue == 4:
self.bg_image.source = 'green.jpg'
基维:
我意识到globals可能非常危险,我宁愿不使用它们,但我不知道它还能起什么作用。另外,我想知道如何在Kivy中更改Python全局变量,然后在第二个类中使用它们来确定屏幕背景。您尝试使用第一个屏幕中的值:
<End>:
id: end
name: "end"
endbtn: endbtn
bg_image: bg_image
on_pre_enter:
self.which_color(self.manager.get_screen('start').startvalue)
解决方案是使用Kivy NumericProperty并将其连接起来。有关详细信息,请参考下面的示例 实例 main.py 试验电压(千伏) 输出
如果已经在使用类,则根本不需要全局变量。在def _init__self:部分将startvalue指定为self.startvalue,您将能够在构造函数或实例中的任何位置访问它。@AdamCottrell-没问题,伙计
<End>:
id: end
name: "end"
endbtn: endbtn
bg_image: bg_image
on_pre_enter:
self.which_color(self.manager.get_screen('start').startvalue)
def which_color(self, startvalue):
...
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import NumericProperty
class ScreenManagement(ScreenManager):
pass
class Start(Screen):
startvalue = NumericProperty(0)
class End(Screen):
def which_color(self, startvalue):
print("startvalue={}".format(startvalue))
if startvalue == 1:
self.bg_image.source = 'blue.png'
elif startvalue == 2:
self.bg_image.source = 'red.png'
elif startvalue == 3:
self.bg_image.source = 'yellow.jpg'
elif startvalue == 4:
self.bg_image.source = 'green.jpg'
class TestApp(App):
def build(self):
return ScreenManagement()
if __name__ == "__main__":
TestApp().run()
#:kivy 1.10.0
<ScreenManagement>:
Start:
id: start
End:
startvalue: start.startvalue
<Start>:
name: 'start'
BoxLayout:
Button:
name: 'btn1'
id: btn1
text: "btn1"
on_release:
root.startvalue = 1
app.root.current = 'end'
Button:
name: 'btn2'
id: btn2
text: "btn2"
on_release:
root.startvalue = 2
app.root.current = 'end'
Button:
name: 'btn3'
id: btn3
text: "btn3"
on_release:
root.startvalue = 3
app.root.current = 'end'
Button:
name: 'btn4'
id: btn4
text: "btn4"
on_release:
root.startvalue = 4
app.root.current = 'end'
<End>:
id: end
name: "end"
endbtn: endbtn
bg_image: bg_image
on_pre_enter: self.which_color(root.startvalue)
Image:
id: bg_image
source: ""
allow_stretch: True
Button:
name: 'endbtn'
id: endbtn
text: "end"
size_hint_y: .35
size_hint_x: .25
on_release: app.root.current = 'start'