user1592380
user1592380

Reputation: 36327

Destroy Tkinter button after click

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?

Upvotes: 0

Views: 3599

Answers (2)

Grasshopper
Grasshopper

Reputation: 436

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

Upvotes: 1

Nae
Nae

Reputation: 15345

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.

Upvotes: 2

Related Questions