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

Mik*_*lta 2 python function button kivy

我在使用kivy库方面很新。

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

app.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()
Run Code Online (Sandbox Code Playgroud)

app.kv:

#:kivy 1.9.1

<Launch>:
    BoxLayout:
        Button:
            size:(80,80)
            size_hint:(None,None)
            text:"Click me"
            on_press: say_hello
Run Code Online (Sandbox Code Playgroud)

End*_*ook 6

模式:.kv

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

另外,如果say_helloApp课堂上,您应该使用,App.say_hello()因为它属于应用程序。(注意:即使您的App类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()
Run Code Online (Sandbox Code Playgroud)

模式: .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"
Run Code Online (Sandbox Code Playgroud)

为什么要使用bind?对不起,不知道 但是您在kivy指南中使用了它


inc*_*ent 2

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

on_press: root.say_hello()
Run Code Online (Sandbox Code Playgroud)

另请注意,您必须实际调用该函数,而不仅仅是编写其名称 - 冒号右侧的所有内容都是正常的 Python 代码。