python - 如何获取kivy中按下的按钮的ID?
问题描述
这是我正在使用的示例代码。
我正在基于 for 循环创建预设数量的按钮,每个按钮都有自己的 ID 号
按下时,所有按钮都具有相同的功能
我的目标是获取按下按钮的 ID 名称
目前,我的代码正在打印出特定的对象地址(?),如 0xAABBCCEE
我想知道如何以 ID 格式打印代码,例如“Button 3”
class MainScreen(GridLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.cols = 1
MainScreenLayout = GridLayout()
MainScreenLayout.cols = 3
#for loop creating buttons with varying IDs
NumberToCreate = 4
for x in range(int(NumberToCreate)):
aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
MainScreenLayout.add_widget(aButton)
self.ids['button' + str(x)] = aButton
self.add_widget(MainScreenLayout)
#function for when button is pressed
def press_auth(self, instance):
print(str(instance)) #ulimate goal is get ID name and x number, to use later in code
class MyApp(App):
def build(self):
return MainScreen()
if __name__== '__main__':
MyApp().run()
解决方案
kivy 中的 ID 通常与 kv 文件结合使用,以通过继承跟踪对象。您可能不应该ids
像您一样将实例变量用作 setter,因为它通常在内部设置为 kivy 并被开发人员用作 getter。
一种更简单的方法是在每个 Button 实例上设置一个任意变量并跟踪那里的差异。如果您打算使用深度继承,这就是您想要使用的原因,ids
那么我会id
在将实例添加到MainScreen
.
第一种方法可以像这样简单地完成:
class MainScreen(GridLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.cols = 1
MainScreenLayout = GridLayout()
MainScreenLayout.cols = 3
#for loop creating buttons with varying IDs
NumberToCreate = 4
for x in range(int(NumberToCreate)):
aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
aButton.my_id = x # or 'button' + str(x) or whatever you want to use to track buttons
MainScreenLayout.add_widget(aButton)
self.add_widget(MainScreenLayout)
#function for when button is pressed
def press_auth(self, instance):
print(str(instance.my_id)) #ulimate goal is get ID name and x number, to use later in code
class MyApp(App):
def build(self):
return MainScreen()
if __name__== '__main__':
MyApp().run()
推荐阅读
- git - Dockerfile - “主机密钥验证失败...”错误
- r - 带有 2 个类别和原始计数的华夫饼图用神秘的第 3 类组成数据填充最后一列
- python - pytz 不更新时区更改的时间
- javascript - 在 d3.js 中加载 csv 时“data.forEach 不是函数”
- php - 使用 file_get_contents 时出错,返回 null
- binary-tree - 试图在 Leetcode 中理解这个二叉搜索树。号码排列看起来不对
- sql - 当相关表使用多对一关系时,有没有办法使用 Power BI 中相关表的内容过滤表的行?
- typescript - 可以推断参数类型的嵌套对象的键吗?
- java - 使用 chromedriver 查找包含文本 IMG、Java Selenium 的 Spans
- qt - QML 中的结构化常量