How to use a <ComboboxSelected> virtual event with tkinter How to use a <ComboboxSelected> virtual event with tkinter tkinter tkinter

How to use a <ComboboxSelected> virtual event with tkinter


The problem is not with the event <<ComboboxSelected>>, but the fact that bind function requires a callback as second argument.

When you do:

cbox.bind("<<ComboboxSelected>>", print("Selected!"))

you're basically assigning the result of the call to print("Selected!") as callback.

To solve your problem, you can either simply assign a function object to call whenever the event occurs (option 1, which is the advisable one) or use lambda functions (option 2).

Here's the option 1:

import tkinter as tkfrom tkinter import ttktkwindow = tk.Tk()cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')cbox.grid(column=0, row=0)def callback(eventObject):    print(eventObject)cbox.bind("<<ComboboxSelected>>", callback)tkwindow.mainloop()

Note the absence of () after callback in: cbox.bind("<<ComboboxSelected>>", callback).

Here's option 2:

import tkinter as tkfrom tkinter import ttktkwindow = tk.Tk()cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')cbox.grid(column=0, row=0)cbox.bind("<<ComboboxSelected>>", lambda _ : print("Selected!"))tkwindow.mainloop()

Check what are lambda functions and how to use them!

Check this article to know more about events and bindings:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm


Thanks you for the posts. I tried *args and it workes with bind and button as well:

import tkinter as tkfrom tkinter import ttktkwindow = tk.Tk()cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')def callback(*args):    print(eventObject)cbox.bind("<<ComboboxSelected>>", callback)btn = ttk.Button(tkwindow, text="Call Callback", command=callback);tkwindow.mainloop()