python 基维 : how to call a function on button click?

标签 python function button kivy

我对使用 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()

应用.kv:

#:kivy 1.9.1

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

最佳答案

模式:.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()

模式:.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 .

关于 python 基维 : how to call a function on button click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46351997/

相关文章:

Python 列表作为变量名

python - 使用 findall() 方法解析简单的数学方程

Javascript 多合一函数在数组中查找值

c++ - 捕获函数标准输出并将其写入文件

javascript - 我无法用 javascript 做一个简单的计算器

python - 计算屏幕DPI

python - Python 3 IP网络摄像头字节错误

javascript - var myFunction = function 函数名()

css - Bootstrap 4 边框重叠按钮元素

javascript - 如何通过文本框数组提交按钮