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?

Pwnosaurus
  • 2,058
  • 1
  • 19
  • 21
user1592380
  • 34,265
  • 92
  • 284
  • 515
  • This is not an [MCVE](https://stackoverflow.com/help/mcve). What is `window` at the very least? – Nae Dec 27 '17 at 18:15

2 Answers2

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.

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

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

Grasshopper
  • 363
  • 2
  • 14