Search code examples
pythontkintercombobox

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


I have a window with 8 combo boxes (which can change based on user input), and I am trying to attach a bind function to each combo box. Since the number of combo boxes is variable, I created a list of combo box widgets. Here's a snippet of my code:

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

How do I make sure that when I select the first combo box, the appropriate value pops up? I know it has something to do with the index, but I can't seem to put my finger on it.


Solution

  • You can just use event.widget in testPop():

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

    Better move the testPop() function out of the for loop.