我制作了两个具有相同功能路径的按钮。虽然只有一个按钮可以使用。两个按钮都应更改lines
中的circle
。
我在另一篇文章中读到,我可能需要将两个类“链接”在一起,以便它们可以“交谈”。如果有人有任何见识,请告诉我!
此外,为什么print
功能在两个按钮上都起作用,而其余部分却不能起作用?
Py:
from kivy.app import App
from kivy.properties import ListProperty
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class Screen1(Screen):
pass
class SM(ScreenManager):
pass
class ButtonX(Button):
def increaseX(self):
TestApp().increase()
class TestApp(App):
random_num_list = ListProperty([20, 40, 80])
def increase(self):
print(str(self.random_num_list))
self.random_num_list = [90, 140, 220]
def build(self):
global sm
sm = SM()
return sm
if __name__ == '__main__':
TestApp().run()
Kv:
<Screen1>:
FloatLayout:
Button:
pos_hint: {'center_x': .5, 'center_y': .5}
canvas:
Color:
rgba: 1,1,1,1
Line:
width: 5
circle: self.center_x, self.center_y, min(self.width, self.height) / 4, 0, app.random_num_list[0]
Color:
rgba: .8,.1,.8,1
Line:
width: 5
circle: self.center_x, self.center_y, min(self.width, self.height) / 4, app.random_num_list[0], app.random_num_list[1]
Color:
rgba: .6,.6,1,1
Line:
width: 5
circle: self.center_x, self.center_y, min(self.width, self.height) / 4, app.random_num_list[1], app.random_num_list[2]
Color:
rgba: 1,.1,.4,1
Line:
width: 5
circle: self.center_x, self.center_y, min(self.width, self.height) / 4, app.random_num_list[2], 360
ButtonX:
pos_hint: {'center_x': .5, 'center_y': .55}
size_hint: .2, .1
text: 'Try first:\ndoesn\'t works'
on_press: self.increaseX()
ButtonX:
pos_hint: {'center_x': .5, 'center_y': .45}
size_hint: .2, .1
text: 'Try second:\nworks'
on_press: app.increase()
<SM>:
Screen1:
答案 0 :(得分:1)
要理解该问题,我将修改代码:
# ...
class ButtonX(Button):
def increaseX(self):
t2 = TestApp()
print("t2", t2)
t2.increase()
# ...
if __name__ == '__main__':
t1 = TestApp()
print("t1", t1)
t1.run()
获取以下信息:
...
t1 <__main__.TestApp object at 0x7f8e750c38d0>
...
t2 <__main__.TestApp object at 0x7f8e71246320>
...
很明显,可以看到它们是2个不同的对象,因此,在调用increase()
时,不会对当前应用程序进行任何修改。
如果.kv用于app
,这是一个指示应用程序正在运行的对象,而等效于.py,则App.get_running_app()
,因此解决方案是使用最后一个元素。
from kivy.app import App
from kivy.properties import ListProperty
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class Screen1(Screen):
pass
class SM(ScreenManager):
pass
class ButtonX(Button):
def increaseX(self):
App.get_running_app().increase() # <---
class TestApp(App):
random_num_list = ListProperty([20, 40, 80])
def increase(self):
print(str(self.random_num_list))
self.random_num_list = [90, 140, 220]
def build(self):
sm = SM()
return sm
if __name__ == '__main__':
TestApp().run()
最后,不要使用全局变量,因为它们在调试时很麻烦。