2008-09-21 79 views

回答

93

Tkinter支持名爲protocol handlers的機制。這裏,術語協議是指應用程序和窗口管理器之間的交互。最常用的協議稱爲WM_DELETE_WINDOW,用於定義用戶使用窗口管理器明確關閉窗口時發生的情況。

可以使用方法安裝處理器此協議(小部件必須是TkToplevel小部件):

這裏有一個具體的例子:

import tkinter as tk 
from tkinter import messagebox 

root = tk.Tk() 

def on_closing(): 
    if messagebox.askokcancel("Quit", "Do you want to quit?"): 
     root.destroy() 

root.protocol("WM_DELETE_WINDOW", on_closing) 
root.mainloop() 
+5

我使用了類似的代碼,但是使用了`root.destroy()` – 182764125216 2011-08-03 00:03:34

+2

如果你正在使用像Twisted這樣獨立維護一個事件循環或者Tkinter(例如:twisted的reactor對象)的東西,確保外部主循環被任何smenatics它提供了這個目的(例如:twisted.stop()用於扭曲) – 2012-02-13 16:40:54

-13

使用closeEvent

def closeEvent(self, event): 
# code to be executed 
13

Matt已經顯示了一個經典的修改n關閉按鈕。
另一種是讓關閉按鈕最小化窗口。
您可以通過使iconify方法
成爲protocol方法的第二個參數來重現此行爲。

這裏的工作的例子,在Windows 7測試:

# Python 3 
import tkinter 
import tkinter.scrolledtext as scrolledtext 

class GUI(object): 

    def __init__(self): 
     root = self.root = tkinter.Tk() 
     root.title('Test') 

    # make the top right close button minimize (iconify) the main window 
     root.protocol("WM_DELETE_WINDOW", root.iconify) 

    # make Esc exit the program 
     root.bind('<Escape>', lambda e: root.destroy()) 

    # create a menu bar with an Exit command 
     menubar = tkinter.Menu(root) 
     filemenu = tkinter.Menu(menubar, tearoff=0) 
     filemenu.add_command(label="Exit", command=root.destroy) 
     menubar.add_cascade(label="File", menu=filemenu) 
     root.config(menu=menubar) 

    # create a Text widget with a Scrollbar attached 
     txt = scrolledtext.ScrolledText(root, undo=True) 
     txt['font'] = ('consolas', '12') 
     txt.pack(expand=True, fill='both') 

gui = GUI() 
gui.root.mainloop() 

在這個例子中,我們爲用戶提供了兩個新的退出方式:
傳統的文件菜單 - >退出,也是Esc鍵按鈕。