当我单击和关闭复选框时,布尔值当前已更新,但是当我单击按钮时,它将始终打印我在开始时定义的默认值。我该如何更新类之外的布尔值,以便在单击按钮并调用函数时更新布尔值?
另外,当我单击类之外的按钮时,如何调用这样的函数?
谢谢
someBool = False
def someFunction():
print(someBool)
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
#grid layout constructor
super(MyGridLayout, self).__init__(**kwargs)
#set columns for the layout
self.cols = 2
self.add_widget(Label(text="checkbox"))
self.checkbox= CheckBox(active = False)
self.add_widget(self.checkbox)
#this will bind the label and checkbox
self.checkbox.bind(active = self.checkboxActive)
self.button= Button(text="Button")
self.button.bind(on_press=someFunction)
self.add_widget(self.button)
def checkboxActive(self, checkbox, value):
if value:
someBool = True
else:
someBool = False
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()
如果要在python中的函数外部更改值,则必须指定其范围。可以很容易地做到这一点global variable
。
然后对于按钮,您必须将匿名函数传递给kivyon_press
方法,以将其链接到所需的函数。这样,按下即可触发功能通过。因此,我们将不得不使用lambda
它。
试试这个代码:
someBool = False
def someFunction():
global someBool
print(someBool)
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
# grid layout constructor
super(MyGridLayout, self).__init__(**kwargs)
# set columns for the layout
self.cols = 2
self.add_widget(Label(text="checkbox"))
self.checkbox = CheckBox(active=False)
self.add_widget(self.checkbox)
# this will bind the label and checkbox
self.checkbox.bind(active=self.checkboxActive)
self.button = Button(text="Button")
self.button.bind(on_press=lambda x: someFunction())
self.add_widget(self.button)
def checkboxActive(self, checkbox, value):
global someBool
if value:
someBool = True
else:
someBool = False
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句