python - 如何取消调用python tkinter中的函数?
问题描述
我正在使用 Tkinter 模块在 python 中创建一个提醒应用程序。当用户单击取消提醒按钮时,我需要取消调用该函数。我试图将时间(包含函数调用时的毫秒时间的时间变量)变量分配为 0,但它不起作用。抱歉,对于迟到的响应,我正在创建小示例,这是我可以创建的最小示例。代码:
# example:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
global time
time=0 # not works
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel Remind',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
root.after(time, root.destroy)
mainloop()
如果您理解问题,请回答。
解决方案
您需要保存返回的任务ID .after()
,然后使用该ID.after_cancel()
取消计划任务:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
#global time
#time=0 # not works
root.after_cancel(after_id)
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
# save the ID returned by after()
after_id = root.after(time, root.destroy)
mainloop()
推荐阅读
- react-native - 从 react-native / react-navigation 中的超级组件调用子反应导航道具
- mongodb - 带有或条件的正则表达式查询
- javascript - Jquery - 文件上传插件
- python-3.x - 在 pandas 中每 7 天查找一次运行总数
- ruby-on-rails - 在 ajax 注册 Rails 设计时返回错误
- pyspark - 使用 addFile 时,我得到了 java.io.FileNotFoundException。
- html - Mac上的图片和文字不在同一行
- regex - 子字符串之间的正则表达式拆分文件
- javascript - 如何让这个 Anchor 标签填充下一个 div 之前的空间?
- android - 在数据绑定中找不到属性的设置器