Python Kivy:如何在单击按钮时调用函数?

2024-03-28 17:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始用kivy图书馆。

我有一个app.py文件和一个app.kv文件,我的问题是按钮按下时无法调用函数。

应用程序py:

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class Launch(BoxLayout):
    def __init__(self, **kwargs):
        super(Launch, self).__init__(**kwargs)

    def say_hello(self):
        print "hello"


class App(App):
    def build(self):
        return Launch()


if __name__ == '__main__':
    App().run()

约千伏:

#:kivy 1.9.1

<Launch>:
    BoxLayout:
        Button:
            size:(80,80)
            size_hint:(None,None)
            text:"Click me"
            on_press: say_hello

Tags: 文件frompyimportselfapphellodef
3条回答

say_hello是Launch类的一个方法。在您的kv规则中,Launch类是根小部件,因此可以使用root关键字访问它:

on_press: root.say_hello()

还要注意,您必须实际调用该函数,而不仅仅是编写它的名称——冒号右侧的所有内容都是普通的Python代码。

模式:.kv

很简单,say_hello属于Launch类,因此要在.kv文件中使用它,必须编写root.say_hello。请注意,say_hello是一个要执行的函数,因此您不必忘记()--->;root.say_hello()

另外,如果say_helloApp类中,则应该使用App.say_hello(),因为它属于应用程序。(注意:即使你的应用程序类是class MyFantasicApp(App):,它也总是App.say_hello()app.say_hello()我不记得了,对不起)。

#:kivy 1.9.1

<Launch>:
    BoxLayout:
        Button:
            size:(80,80)
            size_hint:(None,None)
            text:"Click me"
            on_press: root.say_hello()

模式:.py

您可以bind函数。

from kivy.uix.button import Button # You would need futhermore this
class Launch(BoxLayout):
    def __init__(self, **kwargs):
        super(Launch, self).__init__(**kwargs)
        mybutton = Button(
                            text = 'Click me',
                            size = (80,80),
                            size_hint = (None,None)
                          )
        mybutton.bind(on_press = self.say_hello) # Note: here say_hello doesn't have brackets.
        Launch.add_widget(mybutton)

    def say_hello(self):
        print "hello"

为什么要使用bind?对不起,不知道。但你在the kivy guide中用过。

from kivy.app import App

from kivy.uix.button import Button

from kivy.uix.label import Label

class Test(App):

def press(self,instance):
    print("Pressed")
def build(self):
    butt=Button(text="Click")
    butt.bind(on_press=self.press) #dont use brackets while calling function
    return butt

Test().run()

相关问题 更多 >