python按钮调用函数_Python Kivy:如何在按钮点击时调用函数?

1586010002-jmsa.png

i'm pretty new at using kivy library.

I have an app.py file and an app.kv file , my problem is that I can't call a function on button press.

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()

app.kv:

#:kivy 1.9.1

:

BoxLayout:

Button:

size:(80,80)

size_hint:(None,None)

text:"Click me"

on_press: say_hello

解决方案

Mode:.kv

It's very simple, say_hello belongs to the Launch class so in order to use it in your .kv file you have to write root.say_hello. Note that say_hello is a function that you want to execute so you don't have to forget the () ---> root.say_hello().

Also, if say_hello were in App class you should use App.say_hello() because it belongs to the app. (Note: even if your App class were class MyFantasicApp(App): it would always be App.say_hello() or app.say_hello() I don't remember, sorry).

#:kivy 1.9.1

:

BoxLayout:

Button:

size:(80,80)

size_hint:(None,None)

text:"Click me"

on_press: root.say_hello()

Mode: .py

You can bind the function.

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"

Why use bind? Sorry, no idea. But you it's used in the kivy guide.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值