0

I have a Tkinter list box populated with city names. I want to grab the selected value and pass it to subsequent code after the mainloop. I have the following tkinker code:

master = tk.Tk()

variable = StringVar(master)
variable.set(cities_list[0]) # default value

w = OptionMenu(master, variable, *cities_list)
w.pack()

def ok():
    print ("value is:" + variable.get())
    return  variable.get()
    window.destroy()


button = Button(master, text="OK", command=ok)
button.pack()

mainloop()


v_list = variable.get().split('-')

The button is stuck in a loop and will not close. I want to close the button after a selection. I've tried both "window.destroy()" and "master.destroy()"

What am I doing wrong?

1
  • This is not an MCVE. What is window at the very least?
    – Nae
    Dec 27, 2017 at 18:15

2 Answers 2

2

Your button doesn't destroy because its function 'returns' before doing so. Which is also bad because a command's callback method can't really return anywhere meaningful. Do the following changes:

some_outer_scope_var = None

def ok():
    global some_outer_scope_var
    some_outer_scope_var = variable.get()
    print ("value is:" + variable.get())
    master.destroy()

That way you save the value of variable.get() on some_outer_scope_var first and then destroy all GUI.

2
  • It turns out that variable was in the outer scope. I removed "some_outer_scope_var = variable.get()" and it started working. Dec 27, 2017 at 20:01
  • @user61629 Shouldn't be the case unless you have multiple instances of Tk.
    – Nae
    Dec 27, 2017 at 20:10
1

Try using button.destroy() if you want to destroy the button only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.