Skip to content Skip to sidebar Skip to footer

How To Use A Virtual Event With Tkinter

I am using a tkk.Combobox themed widget in Python 3.5.2. I want an action to happen when a value is selected. In the Python docs, it says: The combobox widgets generates a <&l

Solution 1:

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 tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)


defcallback(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 tk
from tkinter import ttk

tkwindow = 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

Solution 2:

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

import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')

defcallback(*args):
    print(eventObject)

cbox.bind("<<ComboboxSelected>>", callback)
btn = ttk.Button(tkwindow, text="Call Callback", command=callback);

tkwindow.mainloop()

Post a Comment for "How To Use A Virtual Event With Tkinter"