user393267
user393267

Reputation:

Use one function for the "ComboboxSelected", to read multiple combobox

I am trying to use the same selection event for multiple combobox; is it possible? I can't find a way to pass to the function, the sender of the event.

    def newselection(self, event, {????}):
        self.selection = self.{????}.get()
        print(self.selection)

    self.combo1 = Combobox(self, width=7)
    self.combo1.bind("<<ComboboxSelected>>", self.newselection({????}))
    self.combo1['values'] = ('a', 'c', 'g', 't')
    self.combo1.place(x=250, y=400)
    self.combo1.state(['readonly'])

    self.combo2 = Combobox(self, width=7)
    self.combo2.bind("<<ComboboxSelected>>", self.newselection({????}))
    self.combo2['values'] = ('X', 'Y', 'XX', 'XY')
    self.combo2.place(x=450, y=400)
    self.combo2.state(['readonly'])

So it doesn't matter what combo is selected, I can use the same function and read the sender so I can allocate the value of the combobox correctly.

Upvotes: 2

Views: 2928

Answers (1)

furas
furas

Reputation: 142631

bind expects function name - it means without () and arguments. But it executes this functionw with event which gives access to widget - event.widget

Working example:

import tkinter as tk
from tkinter import ttk

# --- functions ---

def newselection(event):
    print('selected:', event.widget.get())

# --- main ---

root = tk.Tk()

cb1 = ttk.Combobox(root, values=('a', 'c', 'g', 't'))
cb1.pack()
cb1.bind("<<ComboboxSelected>>", newselection)

cb2 = ttk.Combobox(root, values=('X', 'Y', 'XX', 'XY'))
cb2.pack()
cb2.bind("<<ComboboxSelected>>", newselection)

root.mainloop()

If you need more arguments then you have to use lambda

import tkinter as tk
from tkinter import ttk

# --- functions ---

def newselection(event, other):
    print('selected:', event.widget.get())
    print('other:', other)

# --- main ---

root = tk.Tk()

cb1 = ttk.Combobox(root, values=('a', 'c', 'g', 't'))
cb1.pack()
cb1.bind("<<ComboboxSelected>>", lambda event:newselection(event, "Hello"))

cb2 = ttk.Combobox(root, values=('X', 'Y', 'XX', 'XY'))
cb2.pack()
cb2.bind("<<ComboboxSelected>>", lambda event:newselection(event, "World"))

root.mainloop()

Upvotes: 4

Related Questions