Python 将函数绑定到 Kivy 按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23127203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind function to Kivy button
提问by user3436797
I'm trying to bind the following function to a Button
in Kivy.
我正在尝试将以下函数绑定到Button
Kivy 中的 a。
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()
I've tried
我试过了
class Foo():
def initUI(self):
self.add_widget(Button(text="Auth User and Password", on_press=self.auth))
but this doesn't work. What am I doing wrong?
但这不起作用。我究竟做错了什么?
here is my whole code
这是我的全部代码
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()
采纳答案by paarth batra
Replace line
替换线
self.hello = Button(text="hello", on_press=lambda a:self.auth())
of your code and use this :
你的代码并使用这个:
self.hello = Button(text="hello", on_press=lambda a:self.auth())
Also add below line in auth function to see if its called :)
还要在 auth 函数中添加以下行以查看它是否被调用:)
print "auth called"
and There are many ways to perform a particular task .Above code will be to fix your code in minimum effort , However If you would like to do it in another way . Just use code below .
并且有很多方法可以执行特定任务。上面的代码将以最小的努力修复您的代码,但是如果您想以另一种方式来做。只需使用下面的代码。
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")
self.hello.bind(on_press=self.auth)
self.add_widget(self.hello)
def auth(self,instance):
print "auth called"
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()
回答by dabhaid
If you read the Button documentation, the key seems to be to use the bind
function:
如果您阅读Button 文档,关键似乎是使用该bind
功能:
def callback(instance):
print('The button <%s> is being pressed' % instance.text)
btn1 = Button(text='Hello world 1')
btn1.bind(on_press=callback)
回答by Oliver
I don't think any of the answers are very clear. Neither explains that problem is that the callback given to on_press
gets called with a parameter, the instance of button, so LoginScreen.auth
must accept a parameter after the self
:
我认为任何答案都不是很清楚。两者都没有解释这个问题是on_press
使用参数调用给定的回调函数,按钮的实例,因此LoginScreen.auth
必须在 之后接受一个参数self
:
def auth(self, button):
print('button pressed:', instance)
The problem is notthat on_press
must be given via Button.bind
or that the callback must be a function, it can be a bound method, and the docs cited by other answer and by comments link to ButtonbBhavior
which indicates that OP use of on_press
in constructor was fine:
问题不在于on_press
必须通过Button.bind
或回调必须是函数,它可以是绑定方法,并且其他答案和评论链接引用的文档ButtonbBhavior
表明on_press
在构造函数中使用 OP很好:
self.hello = Button(text="hello", on_press=self.auth)
would have worked if auth
had been as described above.
如果auth
如上所述,就会起作用。
回答by Memmo
I report an example of buttons created dynamically within the main class, and then triggered into a single listener:
我报告了一个在主类中动态创建的按钮示例,然后触发到单个侦听器中:
class allMyApp(TabbedPanel):
def __init__(self, **kwargs):
super(allMyApp, self).__init__(**kwargs)
#[...]
for y in sorted(set(emissionYears)):
btn = Button(text = y,
size_hint_y = None,
height = '48dp',
on_release = lambda btn: self.ids.choseEmissionDate.select(btn.text))
btn.bind(on_press = self.sortByYear)
self.ids.choseEmissionDate.add_widget(btn)
def sortByYear(self, instance):
year = instance.text
print(year)