0

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.

Vik
  • 137
  • 1
  • 8

2 Answers2

2

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.

acw1668
  • 40,144
  • 5
  • 22
  • 34
1

Have your function testPop accept a widget as arg, and force a closure by using 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))

On why you need to force a closure, you can read the answer here.

Henry Yik
  • 22,275
  • 4
  • 18
  • 40