Is there a way to know when a tkinter ComboBox option is clicked?

Viewed 548

In tkinter , Buttons have a parameter called command which causes some function to run whenever the button is clicked.

Is the same possible to do with the options of a tkinter Combobox ?

For example :

I have three options in the tkinter Combobox : #1 , #2 , #3

Now , As soon as #1 is or clicked , I want to print something like Options 1 Selected.

Is it possible to do ?

P.S , As @Atlas435 pointed out about getting the selected value from the tk.Combobox() , I really dont want the value of the Combobox() , what I am asking is that whether there is way to make Combobox options work like Buttons which when clicked , causes some function to execute.

1 Answers

Take a look at this example, which does what you are asking for:

from tkinter import *
from tkinter import ttk

root = Tk()

def select(event): #the function to get triggered each time you choose something
    if c.get() == lst[0]: #if it is the first item
        print('Option 1 is selected')
    elif c.get() == lst[1]: #if it is the second item
        print('Option 2 is selected')
    else: #or if it is the third item
        print('Option 3 is selected')

lst = ['#1','#2','#3'] #creating option list

c = ttk.Combobox(root,values=lst,state='readonly') #creating a combobox
c.current(0) #setting first element as the item to be showed
c.pack(padx=10,pady=10) #putting on screen

c.bind('<<ComboboxSelected>>',select) #the event that your looking for 

root.mainloop()

Ive commented it to understand better, if any doubts or errors, do let me know

Related