本文介绍了为什么使用“frame.quit"关闭 tkinter 子窗口会退出我的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个窗口的 tkinter 应用程序:一个在启动时创建的 MainWindow 和一个在单击后打开的 ChildWindow按钮.

I have a tkinter application with two windows: A MainWindow that is created on startup, and a ChildWindow which is opened after clicking a button.

如果用户按下按钮,ChildWindow 应该自行关闭.但是,当我尝试调用 frame.quit 时,它会终止整个应用程序.

The ChildWindow should close itself if the user presses a button. However, when I try calling frame.quit, it terminates the entire application instead.

import tkinter as tk

class ChildWindow:
    def __init__(self, master):
        self.top = tk.Toplevel(master)
        self.frame = tk.Frame(self.top)
        self.frame.pack()
        # BUG: Clicking "Close" will fully exit application
        self.close_button = tk.Button(self.frame, text="Close", command=self.frame.quit)
        self.close_button.pack()

class MainWindow:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.about_button = tk.Button(self.frame, text="Open child window", command=self._open_child_window)
        self.about_button.pack()
        self.frame.pack()

    def _open_child_window(self):
        self.about_window = ChildWindow(self.master)

root = tk.Tk()
lf = MainWindow(root)
root.mainloop()

截图:

为什么 frame.quit 退出我的应用程序?如何在不退出的情况下关闭子窗口?

Why does frame.quit exit my application? How can I close the child window without exiting?

推荐答案

是因为 quit 导致 mainloop 退出.在没有事件循环运行的情况下,没有任何东西可以让主窗口保持活动状态.

It is because quit causes mainloop to exit. With no event loop running, there's nothing left to keep the main window alive.

如果要关闭子窗口,请调用destroy 方法.

If you want to close a child window, call the destroy method.

self.close_button = tk.Button(..., command=self.top.destroy)

这篇关于为什么使用“frame.quit"关闭 tkinter 子窗口会退出我的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 16:48