我正在尝试将以下函数绑定(bind)到 Kivy 中的 Button
。
def auth(self):
print(self.username)
if self.username == "Hendricko":
print("self.username == Hendricko")
popup = Popup(title="success",
content=Label(text="Howdy !"),
size=(100, 100),
size_hint=(0.3, 0.3),
auto_dismiss=False)
popup.open()
我试过了
class Foo():
def initUI(self):
self.add_widget(Button(text="Auth User and Password", on_press=self.auth))
但这行不通。我做错了什么?
这是我的全部代码
from kivy.uix.popup import Popup
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.cols = 2
self.row = 2
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
self.hello = Button(text="hello", on_press=self.auth)
self.add_widget(self.hello)
def auth(self):
if self.username == "Hendricko":
popup = Popup(title="success",
content=Label(text="Howdy !"),
size=(100, 100),
size_hint=(0.3, 0.3),
auto_dismiss=False)
popup.open()
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
最佳答案
我认为没有任何答案是非常明确的。两者都没有解释这个问题是给 on_press
的回调是用一个参数调用的,按钮的实例,所以 LoginScreen.auth
必须在 self 之后接受一个参数
:
def auth(self, button):
print('button pressed:', instance)
问题是不是 on_press
必须通过Button.bind
给出,或者回调必须是一个函数,它可以是一个绑定(bind)方法,以及其他答案和评论引用的文档链接到 ButtonbBhavior
这表明 OP 在构造函数中使用 on_press
是好的:
self.hello = Button(text="hello", on_press=self.auth)
如果 auth
已经如上所描述的那样将会工作。
关于python - 将函数绑定(bind)到 Kivy 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127203/