如何处理 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”,通过单击它,我们可以关闭主窗口。

更新时间:2021-3-27

6K+ 浏览次数

启动您的 职业生涯

完成课程可获得认证

开始
广告
© . All rights reserved.