Home > other >  tkinter get selected element from combobox without button
tkinter get selected element from combobox without button

Time:06-15

I'm trying to find a way to get the tkinter combobox selected element without using a button, or to get the value from command in button, however so far nothing is working for me.

here's an example code (that's not working):

def show_frame(frame, prev_frame):

    selected_elem = combobox.get()

    if selected_elem == "choose element":
        label = Label(frame1, text="please choose an element!")
        label.grid(row=4, column=0)

    else:
        prev_frame.grid_forget()
        frame.grid(row=0, column=0, sticky='nsew')

    return selected_elem

elem= ""
button = Button(frame1, text="enter", command=lambda: elem==show_frame(frame3, frame1))
button.grid(row=2, column=1, padx=10, pady=10)

Is there a way to get it also outside of this function? this was just an idea that I had but as I mentioned, it's not working...

CodePudding user response:

You need the bind method to watch for a selected element:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.title("Combobox")

selected_elem = tk.StringVar(value='value1')
combobox = ttk.Combobox(root, textvariable=selected_elem)
combobox['values'] = ('value1', 'value2', 'value3')
combobox.pack(fill=tk.X, padx=20, pady=20)

myLabel = tk.Label(root, text=selected_elem.get())
myLabel.pack()

# prevent typing a value
combobox['state'] = 'readonly'

# place the widget
combobox.pack(fill=tk.X, padx=5, pady=5)


# bind the selected value changes
def value_changed(event):
    """ handle the value changed event """
    myLabel.configure(text=selected_elem.get())
    myLabel.pack()


combobox.bind('<<ComboboxSelected>>', value_changed)

root.mainloop()

more info here: https://www.pythontutorial.net/tkinter/tkinter-combobox/

  • Related