如何取消调用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()

如果你明白问题,请回答。

acw1668

您需要保存返回的任务ID .after(),然后使用ID with.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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章