Search code examples
pythontkintercomboboxttk

Get combobox value in python


I'm developing an easy program and I need to get the value from a Combobox. It is easy when the Combobox is in the first created window but for example if I have two windows and the Combobox is in the second, I am not able read the value from that.

For example :

from tkinter import *
from tkinter import ttk

def comando():
    print(box_value.get())

parent = Tk() #first created window
ciao=Tk()     #second created window
box_value=StringVar()
coltbox = ttk.Combobox(ciao, textvariable=box_value, state='readonly')
coltbox["values"] = ["prova","ciao","come","stai"]
coltbox.current(0)
coltbox.grid(row=0)
Button(ciao,text="Salva", command=comando, width=20).grid(row=1)
mainloop()

If I change the parent of the widget from ciao to parent it works! Can anyone explain me?


Solution

  • You cannot have two Tk() windows. one must be Toplevel.

    To get the variable you can do box_value.get()

    Example of a drop down box :

    class TableDropDown(ttk.Combobox):
        def __init__(self, parent):
            self.current_table = tk.StringVar() # create variable for table
            ttk.Combobox.__init__(self, parent)#  init widget
            self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"])
            self.current(0) # index of values for current table
            self.place(x = 50, y = 50, anchor = "w") # place drop down box 
            print(self.current_table.get())