Search code examples
python-3.xtkintercomboboxgetttk

Retrieve choosen value of a ttk.combobox


I am creating a user interface where there is a first window that ask the user to choose a parameter within a list of choices. Here is an MWE :

from tkinter import *
import tkinter.ttk as ttk

Port=''
root = Tk()

PortCOM = ttk.Combobox(root, values=[1,2,3,4,5,6])
PortCOM.bind("<<ComboboxSelected>>",Port)
PortCOM.pack ()

root.mainloop()

print(Port)

So i already tried that but also :

Port = PortCOM.get
Port = PortCOM.cget

With that last try, i get that error message :

<bound method Misc.cget of <tkinter.ttk.Combobox object .!combobox>>

For example, if the user choose the value '4' in my list of values, i want it to be stored in the variable 'Port'.


Solution

  • And if you don't want extra button you can just do this

    from tkinter import *
    import tkinter.ttk as ttk
    
    Port=''
    root = Tk()
    
    def set_port(_):
        global Port
        Port = PortCOM.get()
        print(Port)
    
    PortCOM = ttk.Combobox(root, values=[1,2,3,4,5,6])
    PortCOM.bind("<<ComboboxSelected>>", set_port)
    PortCOM.pack ()
    
    root.mainloop()