如何处理 Tkinter 中的窗口关闭事件?
Tkinter 提供了一个定制的处理程序来关闭窗口。它充当一个回调函数,用户可以使用它来关闭窗口。
要使用处理程序关闭窗口,我们可以使用 destroy() 方法。它在任意函数或任意小组件中调用后立即关闭窗口。让我们通过定义一种方法来调用关闭事件处理程序。
通过在小组件中作为参数使用
示例
#Importing the required library
from tkinter import *
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry
win.geometry("600x400")
#Create a button and pass arguments in command as a function name
my_button= Button(win, text= "X", font=('Helvetica bold', 20),
borderwidth=2, command= win.destroy)
my_button.pack(pady=20)
win.mainloop()通过在函数中调用
#Importing the required library
from tkinter import *
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry
win.geometry("600x300")
#Define a function
def close():
win.destroy()
#Create a button and pass arguments in command as a function name
my_button= Button(win, text= "X", font=('Helvetica bold', 20),
borderwidth=2, command= close)
my_button.pack(pady=20)
win.mainloop()输出
运行上述代码会创建一个按钮“X”,通过单击它,我们可以关闭主窗口。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP