Destroy Tkinter button after click

别说谁变了你拦得住时间么 提交于 2021-01-29 09:03:01

问题


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:


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:


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



来源:https://stackoverflow.com/questions/47996749/destroy-tkinter-button-after-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!