2008-09-21 9 views

답변

93

Tkinter는 protocol handlers이라는 메커니즘을 지원합니다. 여기에서, 용어 프로토콜은 응용 프로그램과 창 관리자 간의 상호 작용을 나타냅니다. 가장 일반적으로 사용되는 프로토콜은 WM_DELETE_WINDOW이며 사용자가 창 관리자를 사용하여 명시 적으로 창을 닫을 때 수행 할 작업을 정의하는 데 사용됩니다.

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

+2

이벤트 루프를 독립적으로 유지하는 Twisted와 같은 것을 사용하거나 Tkinter (예 : twisted 반응기 오브젝트)를 사용하는 경우 외부 메인 루프가 어떤 smenatics (예 : twisted의 경우 reactor.stop()) –

+3

Windows의 Python 2.7에서 'Tkinter'에 하위 모듈 messagebox가 없습니다. 나는'import tkMessageBox as messagebox'를 사용했습니다. – IronManMark20

-13

사용 : 여기

당신이 구체적인 예를 가지고 :

당신은 (위젯이 Tk 또는 Toplevel 위젯이어야 함)이 프로토콜에 대한 처리기를 설치 에 방법을 사용할 수 있습니다 the closeEvent

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

이 답변에 대한 자세한 내용이 필요합니다. 이 선은 어디에 배치됩니까? 내 마지막에 약간 손을 흔들면 작동하지 않을 수 있습니다. – thedayturns

13

Matt는 고전적인 수정 n 닫기 버튼.
다른 하나는 닫기 버튼을 사용하여 창을 최소화하는 것입니다.
iconify 메서드
protocol 메서드의 두 번째 인수로 사용하면이 동작을 재현 할 수 있습니다. > 종료, 또한 Esc를 버튼 -
고전 파일 메뉴 : 우리는 사용자에게 두 개의 새로운 출구 옵션을 제공이 예에서

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

: 여기

은 Windows 7에서 테스트 작업 예입니다 .