我找不到在python代码中设置on_press
的语法,可以在任何地方更改屏幕。我一直在为Button(text = 'hi', on_press = self.current = 'start_menu
之类的东西收到错误。这是代码,它按原样运行。
class LoadMenu(Screen):
def __init__(self, **kwargs):
super(LoadMenu, self).__init__(**kwargs)
Clock.schedule_once(self.update)
def update(self, dt):
L = [x for x in range(len(os.listdir('saves')))]
for x in L:
x = self.add_widget(Button(text = os.listdir('saves')[x]))
我没有定位按钮,所以它们只是在彼此的顶部,但我可以稍后解决。我需要做的是每个按钮在按下时更改为play
屏幕,这对于每个按钮都是相同的,但我还需要每个按钮加载他们引用的Shelve文件。(我知道我'我需要另一个函数)我可以一次on_press
触发两个事件,再次如何在python代码中设置它?
答案 0 :(得分:1)
考虑以下计划:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.properties import StringProperty
dirlist = ['aaa', 'bbb', 'ccc', 'ddd']
class MyButton(Button):
prop = StringProperty('')
def on_press(self):
print "Class-defined on_press handler (I'm {})".format(self.text)
def other_on_press_handler(sender):
print "other_on_press_handler, from {}".format(sender.text)
def some_func(text):
print "yeah: " + text
class LoadMenu(Screen):
def __init__(self, **kwargs):
super(LoadMenu, self).__init__(**kwargs)
Clock.schedule_once(self.update)
def on_press_handler(self, sender):
print "on_press_handler, from {}".format(sender.text)
self.parent.current = 'sc2'
def yet_another_on_press_handler(self, sender):
print "yet_another_on_press_handler, from {}".format(sender.text)
self.parent.current = 'sc2'
def update(self, dt):
for x in range(len(dirlist)):
my_b = Button(text = dirlist[x], on_press=self.on_press_handler)
self.parent.ids.button_container.add_widget(my_b)
if x > 1:
my_b.bind(on_press=other_on_press_handler)
if x == 3:
my_b.bind(on_press=lambda sender: some_func("Whoa, lambda was here ({})".format(sender.text)))
for x in range(len(dirlist)):
my_b = MyButton(text = 'my '+ dirlist[x], prop="{} {}".format(dirlist[x], x))
self.parent.ids.button_container.add_widget(my_b)
my_b.bind(on_press=self.yet_another_on_press_handler)
root = Builder.load_string("""
ScreenManager:
LoadMenu:
name: 'sc1'
GridLayout:
cols: 4
id: button_container
Screen:
name: 'sc2'
BoxLayout:
Button:
text: "Go back"
on_press: root.current = 'sc1'
""")
class MyApp(App):
def build(self):
return root
if __name__ == '__main__':
a = MyApp()
a.run()
让我们从查看update
中的LoadMenu
方法开始:在第一个循环中,生成一堆按钮,每个按钮在创建时都会收到on_press
回调。循环中的最后两个按钮绑定到另一个回调,最后一个示例显示如何使用lambda表达式生成回调。
在第二个for循环中,我们实例化了MyButton
的对象,Button
的子对象。注意,我们还在类定义中定义了一个on_press
处理程序;除了我们可能绑定的其他函数之外,还会调用它。
但实际上,这实际上在kivy Events and Properties docs中已经很好地解释了。