检查顶层窗口是否已关闭?

huangapple go评论71阅读模式
英文:

check if Toplevel windows was closed?

问题

我正在尝试找出代码,用于检查"Extra"窗口是否已关闭。我一直在查找,似乎找不到任何有用的信息。有没有办法做到这一点?

英文:

I have a tkinter app, created with customtkinter:

import customtkinter

class App(customtkinter.CTk):
	def __init__(self):
		super().__init__()
		Extra()

		self.mainloop()

class Extra(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry("400x300")

        self.label = customtkinter.CTkLabel(self, text="ToplevelWindow")
        self.label.pack(padx=20, pady=20)

App() 

I am trying to figure out code that checks if the Extra window has been closed. I've been looking around and cannot seem to find anything useful. Is there a way of doing this?

答案1

得分: 3

根据此线程中的答案https://stackoverflow.com/questions/111155/how-do-i-handle-the-window-close-event-in-tkinter:

如果在您尚未定义处理程序的情况下收到WM_DELETE_WINDOW消息,则Tk将通过销毁接收到该消息的窗口来处理该消息。

我们可以添加名为WM_DELETE_WINDOWprotocol,并使用self.destroy()方法,如下所示:

class Extra(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry("400x300")
        self.label = customtkinter.CTkLabel(self, text="ToplevelWindow")
        self.label.pack(padx=20, pady=20)

        self.protocol("WM_DELETE_WINDOW", self.closed) # <-- 添加协议

    def closed(self):
        print("我已经关闭了!")
        self.destroy()

结果是:

我已经关闭了!

然后我们终止额外的窗口。

英文:

Based on answers in this thread https://stackoverflow.com/questions/111155/how-do-i-handle-the-window-close-event-in-tkinter:

>If a WM_DELETE_WINDOW message arrives when you haven't defined a handler, then Tk handles the message by destroying the window for which it was received.

We could add a protocol named WM_DELETE_WINDOW and use the self.destroy() method as such:

class Extra(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry(&quot;400x300&quot;)
        self.label = customtkinter.CTkLabel(self, text=&quot;ToplevelWindow&quot;)
        self.label.pack(padx=20, pady=20)

        self.protocol(&quot;WM_DELETE_WINDOW&quot;, self.closed) # &lt;-- adding the protocol

    def closed(self):
        print(&quot;I&#39;ve been closed!&quot;)
        self.destroy()

检查顶层窗口是否已关闭?


Resulting in:

I&#39;ve been closed!

And we then terminate the extra window.

huangapple
  • 本文由 发表于 2023年2月10日 03:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定