how to close a tkinter window without terminating the program?

江枫思渺然 提交于 2021-02-08 12:06:51

问题


i have a project that i am working on for class and i am using tkinter to build my basic GUI. when i run the code i have two drop down menus to choose options from. i also want a button to close the window and advance the program to the next GUI window. however i can not get a button to close the window without also causing the program to terminate. here is my code

from tkinter import *

Options_year = ["2014", "2013", "2012", "2011", "2010"]
Options_month = ["January","February", "March", "April","May", "June", "July","August","September","October","November",
                 "December"]
master = Tk()
variable_year = StringVar(master)
variable_year.set(Options_year[0])
variable_month = StringVar(master)
variable_month.set(Options_month[0])
window = apply(OptionMenu, (master, variable_year) + tuple(Options_year))
window_month = apply(OptionMenu, (master,variable_month) + tuple(Options_month))
window.pack()
window_month.pack()
button = Button(master, text = "Continue", command = master.quit())
#the line above is the button that i want to use to close the window
button.pack()
mainloop()
print (variable_month.get())
print (variable_year.get())

EDIT: converted this to a frame and used the supplied answer below and got it to work. thanks to every one who helped me


回答1:


Use a Toplevel or frame, put the widgets in it, and destroy() it. You can use master.withdraw() or iconify() if you do not want it to show.




回答2:


Destroying the gui also destroys tk Variables. I strongly suspect that you omitted the vital information that the program terminates with a exception traceback due to the attempt to access the .get method of the non-longer existent variable_month. The following works fine.

from tkinter import *
root = Tk()
root.mainloop()
print('here')


来源:https://stackoverflow.com/questions/27277257/how-to-close-a-tkinter-window-without-terminating-the-program

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