如何在kivy中打印按下的按钮名称
我是 kivy 的新手,我“生成”了 20 个按钮,我想在按下按钮时使用名为“on_press_kartya”的函数打印按钮的名称,但我不知道该怎么做。我将不胜感激任何帮助。
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import random
class MainApp(App):
def build(self):
self.startbutton = Button(text='Start',
size_hint=(.2, .2),
pos_hint={'center_x': .5, 'center_y': .5})
self.startbutton.bind(on_press=self.on_press_startbutton)
boxlayout = BoxLayout()
boxlayout.add_widget(self.startbutton)
return boxlayout
def on_press_startbutton(self, instance):
self.root.remove_widget(self.startbutton)
self.root.add_widget(self.visszabutton)
start()
for i in range(20):
self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))
def on_press_kartya(self, instance):
print("the name of the pressed button")
I am new to kivy and I "generated" 20 buttons and I want to print the name of the buttons with the function called "on_press_kartya" when they are pressed but I don't know how can I do that. I would appreciate any help.
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import random
class MainApp(App):
def build(self):
self.startbutton = Button(text='Start',
size_hint=(.2, .2),
pos_hint={'center_x': .5, 'center_y': .5})
self.startbutton.bind(on_press=self.on_press_startbutton)
boxlayout = BoxLayout()
boxlayout.add_widget(self.startbutton)
return boxlayout
def on_press_startbutton(self, instance):
self.root.remove_widget(self.startbutton)
self.root.add_widget(self.visszabutton)
start()
for i in range(20):
self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))
def on_press_kartya(self, instance):
print("the name of the pressed button")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的方法
on_press_kartya
是 事件回调您只需传递实例(此处为Button
)并访问其中的属性,同样,如果您使用
lambda
或partial
> 通过一些arg(s) 您可能在回调中还需要一些额外的 arg(s)。Since your method
on_press_kartya
is an event callback you just pass the instance (hereButton
) and access its properties therein as,Also if you use
lambda
orpartial
to pass some arg(s) you may need some extra arg(s) as well in the callback.