Search code examples
python-3.xtkintergettk-toolkitttk

Tkinter Combobox dont get value


I succeeded in applying the combo box to a new window as well. However, it failed to get the value of the combo box through the get() function.

win = tk.Tk()

win.title("win1")
def com():
    win2 = tk.Tk()
    win2.grab_set()
    win.title("win2")
    r_location_value = tk.StringVar()
    location = ttk.Combobox(win2, width=8, textvariable=r_location_value,
                            values=["a", "b", "c", "d", "e", "f", "g", "h", "i","j"])
    v = r_location_value.get()
    print(r_location_value.get())
    def tt():
        v = r_location_value.get()
        print(v)
    
    location.current(0)
    location.pack()
    Button = tk.Button(win2,text="click",command = tt)
    Button.pack()
Button = tk.Button(win,text="click",command = com)
Button.pack()
win.mainloop()

To solve this, I created a new variable and tried to put the get() value, but it failed.


Solution

  • As some others mentioned in the comments, I can't say the structure of this is something I would recommend - however I do have a solution to your issue.

    Use the following in your tt() function to print the selection:

    print(location.get())

    What this is doing, is getting the value associated with the combobox. If you are getting the StringVar it isn't actually grabbing what you are wanting. Alternatively you can use an OptionBox connected to a dictionary that you would then get the StringVar to print and associated value. Hopefully this helps.

    win = tk.Tk()
    
    win.title("win1")
    def com():
        win2 = tk.Tk()
        win2.grab_set()
        win.title("win2")
    
        r_location_value = tk.StringVar()
        location = ttk.Combobox(win2, width=8, textvariable=r_location_value, values=["A", "B", "C"])
    
    
        def tt():
            print(location.get())
        
        location.current(0)
        location.pack()
        Button = tk.Button(win2, text="click", command = tt)
        Button.pack()
    
    Button = tk.Button(win, text="click",command = com)
    Button.pack()
    
    win.mainloop()