[英]How do I bind functions to tkinter widgets that are in a list of variable size?
我有一个带有 8 个组合框的窗口(可以根据用户输入进行更改),我正在尝试将绑定函数附加到每个组合框。 由于组合框的数量是可变的,我创建了一个组合框小部件列表。 这是我的代码片段:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
root=Tk()
root.geometry('300x300')
brandDropdownList=[]
listOfBrands=['Test 1', 'Test 2', 'Test 3']
for i in range(8):
brandDropdownList.append(ttk.Combobox(root, state='readonly', values=listOfBrands, width=10))
brandDropdownList[-1].grid(row=i,column=0)
def testPop(event):
messagebox.showinfo("message",brandDropdownList[-1].get())
brandDropdownList[-1].bind("<<ComboboxSelected>>",testPop)
root.mainloop()
如何确保当我选择第一个组合框时,会弹出相应的值? 我知道它与索引有关,但我似乎无法理解它。
您可以在testPop()
使用event.widget
:
def testPop(event):
messagebox.showinfo("message", event.widget.get())
最好将testPop()
函数移出 for 循环。
让您的函数testPop
接受一个小部件作为 arg,并使用lambda
强制关闭:
for i in range(8):
brandDropdownList.append(ttk.Combobox(root, state='readonly', values=listOfBrands, width=10))
brandDropdownList[-1].grid(row=i,column=0)
def testPop(event, widget):
messagebox.showinfo("message",widget.get())
brandDropdownList[-1].bind("<<ComboboxSelected>>",
lambda e, c=brandDropdownList[-1]: testPop(e, c))
关于为什么需要强制关闭,您可以在此处阅读答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.