2

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.

  • 2
    Yes and there are several questions on it. Search for combpbox and bind selected – Thingamabobs Oct 03 '20 at 19:12
  • 2
    Does this answer your question? [Getting the selected value from combobox in Tkinter](https://stackoverflow.com/questions/31264522/getting-the-selected-value-from-combobox-in-tkinter) – Thingamabobs Oct 03 '20 at 19:13
  • 1
    @Atlas435 , No there is a difference between getting the selected value and "executing a function as soon as an option is clicked" . I can get the value of the ComboBox anytime , thats not an issue. In other words , is there a way to make ComboBox options work like `tkinter Buttons` ? –  Oct 03 '20 at 19:17
  • 2
    Please read it, you will find the line `.bind('<>')` or something like this – Thingamabobs Oct 03 '20 at 19:20
  • 2
    You can bind `` to a function. – acw1668 Oct 04 '20 at 02:43

1 Answers1

4

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

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46