问题
I have created a program in python 3.4 using the GUI module tkinter. I want to tweak the code so when a new window is called it will close the current window then open up the new window. As at the moment the current window is just placed behind the new window rather than destroying it. I have attempted to use .destroy()
but that prevents the other window opening. I have my procedure which carries out the current window switch below.
def help1(self):
root2=Toplevel(self.master)
HelpWindow= HelpScreen.Help(root2)
I understand this question is quite common but i cant find a soloution on here which would be applicable for my code.
回答1:
You can destroy a toplevel window with the destroy()
method. You shouldn't do this on the root window, but you can do it on any other window.
If you only ever want one window in your application, create a root window and then hide it and don't use it. Then, create the first real window as a Toplevel
. From that point on you can easily destroy the current window and create a new window.
Here is a contrived example:
import tkinter as tk
root = tk.Tk()
root.withdraw()
current_window = None
def replace_window(root):
"""Destroy current window, create new window"""
global current_window
if current_window is not None:
current_window.destroy()
current_window = tk.Toplevel(root)
# if the user kills the window via the window manager,
# exit the application.
current_window.wm_protocol("WM_DELETE_WINDOW", root.destroy)
return current_window
counter = 0
def new_window():
global counter
counter += 1
window = replace_window(root)
label = tk.Label(window, text="This is window %s" % counter)
button = tk.Button(window, text="Create a new window", command=new_window)
label.pack(fill="both", expand=True, padx=20, pady=20)
button.pack(padx=10, pady=10)
window = new_window()
来源:https://stackoverflow.com/questions/35434654/closing-current-window-when-opening-another-window