Skip to main content
 首页 » 编程设计

Python Tkinter 对 self.quit 或 sys.exit 安全吗

2024年10月24日38jirigala

本着解耦的精神,我没有将许多小部件塞进一个巨大的类中,而是尝试将它们拆分为单独的类。

我遇到的问题是 FileMenu 类不知道 root,因此不能调用 root.quit 或 root.destroy。一时兴起,我尝试了 self.quit,它起作用了,但我以前从未见过它被使用过。

我的问题是:

  1. self.quit 是退出应用程序的安全方法吗?
  2. sys.exit 是退出应用程序的安全方法吗?
  3. 如果两者都不安全,是否有一种好的方法可以使设计解耦并安全退出,而无需将 root 作为参数传递到任何地方或使其成为全局参数?

我的例子:

import Tkinter as tk 
 
class FileMenu(tk.Menu): 
    def __init__ (self, parent): 
        tk.Menu.__init__(self, parent, tearoff=False) 
        self.add_command(label='Exit', command=self.quit) 
 
class MainMenu(tk.Menu): 
    def __init__ (self, parent): 
        tk.Menu.__init__(self, parent, tearoff=False) 
        self.file_menu = FileMenu(self) 
        self.add_cascade(label='File', menu=self.file_menu) 
 
class View: 
    def __init__ (self, parent): 
        self.frame = tk.Frame(parent) 
        self.parent = parent 
        self.menu = MainMenu(self.frame) 
        self.parent.configure(menu=self.menu) 
        self.parent.geometry('200x200') 
        self.frame.pack(fill='both', expand=True) 
 
class App: 
    def __init__ (self): 
        self.root = tk.Tk() 
        self.view = View(self.root) 
 
    def run (self): 
        self.root.title('Window Title') 
        self.root.mainloop() 
 
if __name__ == '__main__': 
    app = App() 
    app.run() 

请您参考如下方法:

两者用途不同:

sys.exit(): Close complete application.

self.quit: If you have multiple windows in your application and you don't want to close your whole application then you should use self.quit().

Both are safe to use but uses are different.