python destroy函数_Python Tkinter destroy()用法及代码示例

本文介绍了Python Tkinter库中的destroy()方法,用于销毁窗口和小部件。通过示例展示了如何将destroy()作为命令传递给按钮,以及结合after()方法实现定时销毁。文中提供了两个代码示例,分别演示了点击按钮时销毁父窗口和设定时间后自动销毁按钮的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tkinter支持多种执行各种任务的方法。它还提供了一些通用方法。

destroy()是一种通用的窗口小部件方法,即我们可以将此方法与任何可用的窗口小部件以及主tkinter窗口一起使用。

用法:

widget_object = Widget(parent, command = widget_class_object.destroy)

此方法可以与after()方法一起使用。

代码1:作为命令传递的destroy()方法

# importing only those functions

# which are needed

from tkinter import *

from tkinter.ttk import *

# creating tkinter window

root = Tk()

# Creating button. In this destroy method is passed

# as command, so as soon as button 1 is pressed root

# window will be destroyed

btn1 = Button(root, text ="Button 1", command = root.destroy)

btn1.pack(pady = 10)

# Creating button. In this destroy method is passed

# as command, so as soon as button 2 is pressed

# button 1 will be destroyed

btn2 = Button(root, text ="Button 2", command = btn1.destroy)

btn2.pack(pady = 10)

# infinite loop

mainloop()

输出:

如您所见,在上面的代码中,在button-2中传递的命令是销毁button-1,因此,一旦您按一下button-2,button-2就会被销毁。

代码2:destroy()方法和after()方法

# importing only those functions

# which are needed

from tkinter import *

from tkinter.ttk import *

# creating tkinter window

root = Tk()

# Creating button. In this destroy method is passed

# as command, so as soon as button 1 is pressed root

# window will be destroyed

btn1 = Button(root, text ="Button 1")

btn1.pack(pady = 10)

# Creating button. In this destroy method is passed

# as command, so as soon as button 2 is pressed

# button 1 will be destroyed

btn2 = Button(root, text ="Button 2")

btn2.pack(pady = 10)

# after method destroying button-1

# and button-2 after certain time

btn1.after(3000, btn1.destroy)

btn2.after(6000, btn2.destroy)

# infinite loop

mainloop()

输出:

从输出中,您可能会看到在一定时间限制后两个小部件都被销毁,只有根窗口将留空。

注意:还有另一种方法quit()它不会销毁小部件,但会退出tcl /tk解释器,即会停止mainloop()。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值