[英]Python Kivy: Problem with dynamically assigning widget ids
我在 Kivy 中编写了一个应用程序,它会自动添加按钮并使用 for 循环为它们提供唯一的 ID。 然后,此 id 用作链接字典中的键。 所以字典工作正常,打印后,它输出{'button0': 'somewebsite', 'button1': 'other website', 'button2': 'andanotherwebsite'}
这正是我想要的,但按钮callback
function 总是打印出button2
而不是它自己的 id。 我分配的ID错了吗? 下面的示例演示了我的问题。
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivymd.utils import asynckivy
from kivy.clock import Clock
class TestButton(Button):
def callback(self):
print(self.id)
class RootWidget(BoxLayout):
def __init__(self):
super().__init__()
self.links = ["somewebsite", "other website", "andanotherwebsite"]
self.dic_btn_to_lnk = {}
self.size_hint = (None, None)
self.size = ("600dp", "50dp")
Clock.schedule_once(self.add_widgets, 0)
def add_widgets(self, *args):
async def update():
number = 0
for link in self.links:
button = TestButton()
button.text = link
button.size = ("200dp", "50dp")
button.pos_hint = {"center_x": .5}
btn_id = "button" + str(number)
button.id = btn_id
button.bind(on_release=lambda x: button.callback())
number += 1
self.dic_btn_to_lnk[btn_id] = link
self.add_widget(button)
print(self.dic_btn_to_lnk)
asynckivy.start(update())
class TestApp(App):
def build(self):
return RootWidget()
if __name__ == '__main__':
TestApp().run()
问题是您的on_release
绑定正在调用button.callback()
,并且button
将是触发on_release
时添加的最后一个Button
。 解决方案是使用partial
,它在执行partial
时将其 arguments 冻结为其值,因此on_release
调用正确的button.callback
。 像这样:
button.bind(on_release=partial(button.callback))
并且为了简化上面, callback
的定义改为:
class TestButton(Button):
def callback(self, instance):
print(self.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.