如何在kivy中打印按下的按钮名称
How to print the pressed button name in 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")
由于您的方法 on_press_kartya
是一个 event callback 您只需传递实例(此处 Button
)并访问其中的属性,
def on_press_startbutton(self, instance):
...
for i in range(20):
#self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))
self.root.add_widget(Button(text=str(i), on_press=self.on_press_kartya))
# Then in the callback,
def on_press_kartya(self, instance):
print("the name of the pressed button", instance.text)
此外,如果您使用 lambda
或 partial
传递一些参数,您可能还需要在回调中使用一些额外的参数。
我是 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")
由于您的方法 on_press_kartya
是一个 event callback 您只需传递实例(此处 Button
)并访问其中的属性,
def on_press_startbutton(self, instance):
...
for i in range(20):
#self.root.add_widget(Button(text=str(i), on_press=lambda *args: self.on_press_kartya(text)))
self.root.add_widget(Button(text=str(i), on_press=self.on_press_kartya))
# Then in the callback,
def on_press_kartya(self, instance):
print("the name of the pressed button", instance.text)
此外,如果您使用 lambda
或 partial
传递一些参数,您可能还需要在回调中使用一些额外的参数。