【问题标题】:Closing current window when opening another window打开另一个窗口时关闭当前窗口
【发布时间】:2016-02-16 14:04:07
【问题描述】:

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

    def help1(self):
      root2=Toplevel(self.master)
      HelpWindow= HelpScreen.Help(root2)

我知道这个问题很常见,但我在这里找不到适用于我的代码的解决方案。

【问题讨论】:

  • 不要关闭,禁用它!为什么 ?什么是子窗口关闭类型? grab_set / grab_releasewithdraw / deiconify,您需要处理关闭方法,因为Ex: if sub_window closed by system。需要在主应用程序中添加状态检查器if csub_window is exist
  • 一个应用应该有一个主 Tk() 窗口。当它被摧毁时,游戏结束(如你所见)。对于您想要的,使用withdraw 隐藏主要并创建和销毁Toplevels。或者:创建和销毁放在主窗口中的框架。或者:将多个框架相互叠加,然后 .lift() 将您希望显示的那个。
  • 以前有人问过这样的问题。你可以试着搜索一下。

标签: python user-interface python-3.x tkinter tk


【解决方案1】:

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

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

这是一个人为的例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多