我希望最终创建一个按钮来暂停/启动/结束我作为学习练习构建的pong应用程序。但是,为了首先了解如何创建按钮并为其分配响应的基础,我只想创建一个按钮,该按钮在每次按钮状态更改时通知我。这是我到目前为止拥有的python代码:
import kivy.uix.button as kb
from kivy.app import App
from kivy.uix.widget import Widget
class Button_Widget(Widget):
def callback(instance, value):
print('The button <%s> state is <%s>' % (instance, value))
btn1 = kb.Button(text='Hello World 1')
btn1.bind(on_press=callback)
class ButtonApp(App):
def build(self):
button = Button_Widget()
return button
以及相关的kv文件:
#:kivy 1.0.9
<Button_Widget>:
size: 100, 100
canvas:
Rectangle:
pos = self.pos
size = self.size
到目前为止,我发现的唯一资源是这些(1和2)Kivy turorials,它们并不太有用。或者至少,我对他们的语言还不了解,无法使他们有用
答案 0 :(得分:1)
来看看在kivy中创建按钮的最简单代码
from kivy.app import App
from kivy.uix.button import Button
class your_app_name(App):
def build(self):
button = Button(text="Button")
return button
your_app_name().run()
您还可以通过添加 on_press= function_name 向按钮添加命令或事件
答案 1 :(得分:0)
在Button_Widget()类中,您必须重写构造函数__init__()
,以便可以将按钮控件添加到根控件。有关详细信息,请参阅示例。
Programming Guide » Kivy Basics » Create an application
Programming Guide » Kv language
Event dispatcher » bind()将事件类型或属性绑定到回调。
import kivy.uix.button as kb
from kivy.app import App
from kivy.uix.widget import Widget
class Button_Widget(Widget):
def __init__(self, **kwargs):
super(Button_Widget, self).__init__(**kwargs)
btn1 = kb.Button(text='Hello World 1')
btn1.bind(on_press=self.callback)
self.add_widget(btn1)
def callback(self, instance):
print('The button %s state is <%s>' % (instance, instance.state))
class ButtonApp(App):
def build(self):
return Button_Widget()
if __name__ == "__main__":
ButtonApp().run()
#:kivy 1.10.1
<Button_Widget>:
size: 100, 100
canvas:
Rectangle:
pos: self.pos
size: self.size