ventana ejemplos cerrar python events tkinter window

python - ejemplos - ¿Cómo manejo el evento cerrar ventana en Tkinter?



cerrar ventana tkinter python (4)

Dependiendo de la actividad de Tkinter, finaliza esp. al utilizar Tkinter.after, detener esta actividad con destroy() - incluso al usar el protocolo (), un botón, etc. - perturbará esta actividad (error "al ejecutar") en lugar de simplemente terminarla. La mejor solución en casi todos los casos es usar una bandera. Aquí hay un ejemplo simple y tonto de cómo usarlo (¡aunque estoy seguro de que la mayoría de ustedes no lo necesitan! :)

from Tkinter import * def close_window(): global running running = False print "Window closed" root = Tk() root.protocol("WM_DELETE_WINDOW", close_window) cv = Canvas(root, width=200, height=200); cv.pack() running = True; # This is an endless loop stopped only by setting ''running'' to ''False'' while running: for i in range(200): if not running: break cv.create_oval(i,i,i+1,i+1); root.update()

Esto termina la actividad de gráficos muy bien. Solo necesita comprobar que se running en el (los) lugar (es) correcto (s).

¿Cómo manejo el evento de cierre de ventana (usuario haciendo clic en el botón ''X'') en un programa Python Tkinter?


Matt ha mostrado una modificación clásica del botón de cerrar.
El otro es hacer que el botón Cerrar minimice la ventana.
Puedes reproducir este comportamiento teniendo el método iconify
ser el segundo argumento del método de protocol .

Este es un ejemplo de trabajo, probado en 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()

En este ejemplo, le damos al usuario dos nuevas opciones de salida:
el menú de archivo clásico -> Salir, y también el botón Esc .


Utilice el evento closeEvent

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


Tkinter admite un mecanismo llamado manejadores de protocolo . Aquí, el término protocolo se refiere a la interacción entre la aplicación y el administrador de ventanas. El protocolo más comúnmente utilizado se llama WM_DELETE_WINDOW , y se usa para definir qué sucede cuando el usuario cierra una ventana explícitamente usando el administrador de ventanas.

Puede usar el método de protocol para instalar un controlador para este protocolo (el widget debe ser un widget Tk o Toplevel ):

Aquí tienes un ejemplo concreto:

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