打开另一个窗口时关闭当前窗口 [英] Closing current window when opening another window

查看:90
本文介绍了打开另一个窗口时关闭当前窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 GUI 模块 tkinter 在 python 3.4 中创建了一个程序.我想调整代码,以便在调用新窗口时关闭当前窗口,然后打开新窗口.目前,当前窗口只是放置在新窗口后面而不是销毁它.我试图使用 .destroy() 但这会阻止其他窗口打开.我有我的程序来执行下面的当前窗口切换.

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.

推荐答案

您可以使用 destroy() 方法销毁顶层窗口.您不应该在根窗口上执行此操作,但您可以在任何其他窗口上执行此操作.

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.

如果您只想在应用程序中使用一个窗口,请创建一个根窗口,然后将其隐藏并且不要使用它.然后,创建第一个真实窗口作为 Toplevel.从那时起,您可以轻松地销毁当前窗口并创建一个新窗口.

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.

这是一个人为的例子:

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()

这篇关于打开另一个窗口时关闭当前窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆