[英]How do I add functionality to a button in Kivy
I am trying to add functionality to my buttons in Kivy but it is not working. 我正在尝试向Kivy中的按钮添加功能,但无法正常工作。
Here Is the code for the python file: 这是python文件的代码:
import kivy
kivy.require("1.9.1")
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
class MainMenuApp(App):
def build(self):
return BoxLayout()
def Play(self):
print("Play Button Pressed")
def LeaderBoards(self):
print("Leader Board Button Pressed")
def Credits(self):
print("Credits Button Pressed")
def Settings(self):
print("Settings Button Pressed")
if __name__ == "__main__":
MainMenuApp().run()
And for the kv file: 对于kv文件:
<BoxLayout>:
orientation: "vertical"
spacing: 20
padding: 60, 40
Label:
font_name: "TitleFont.ttf"
font_size: "60sp"
text: "Game Title"
size_hint: 1, 2
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Play"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "LeaderBoards"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Credits"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Settings"
This code makes a screen like this: Image 此代码像这样的画面: 图片
I know I need to use the on_click or the on_release method but I don't know how to connect it to a function in my Python file. 我知道我需要使用on_click或on_release方法,但是我不知道如何将其连接到Python文件中的函数。 my question is different than the other ones on this site because it uses the kv language along with Python instead of just Python
我的问题与该网站上的其他问题有所不同,因为它使用的是kv语言以及Python,而不仅仅是Python
Create a custom class, then access the class' attributtes by root.attribute
创建一个自定义类,然后通过
root.attribute
访问该类的属性
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<MyLayout>:
Button:
text: 'Try me!'
on_release: root.button_pressed()
''')
class MyLayout(BoxLayout):
def button_pressed(self):
print("Button pressed")
class MyApp(App):
def build(self):
return MyLayout()
MyApp().run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.