首页 > 解决方案 > 如何取消调用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()

如果您理解问题,请回答。

标签: pythonuser-interfacetkinter

解决方案


您需要保存返回的任务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()

推荐阅读