如何将函数绑定到可变大小列表中的 tkinter 小部件?

How do I bind functions to tkinter widgets that are in a list of variable size?

我有一个带有 8 个组合框(可以根据用户输入更改)的 window,我正在尝试为每个组合框附加一个绑定函数。由于组合框的数量是可变的,我创建了一个组合框小部件列表。这是我的代码片段:

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()

如何确保在 select 第一个组合框时弹出适当的值?我知道它与索引有关,但我似乎无法确定它。

让您的函数 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))

为什么要强行关闭,可以看答案here

您可以在 testPop() 中使用 event.widget:

def testPop(event):
    messagebox.showinfo("message", event.widget.get())

最好将 testPop() 函数移出 for 循环。