Python tkinter模块中利用after方法启动的函数怎么终止?
(我的意思是,after启动了一个会运行很久的一个函数,它大概是一个while True循环,而我想让它在我想要的时候停止,并且不在那个循环里加东西)
Python tkinter 结束after方法启动的函数
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注引自免费微信小程序:皆我百晓生
在 Python 的 Tkinter 模块中,如果你使用
after方法启动了一个长运行的函数,比如一个无限循环,你可以通过保存一个计时器 ID 来取消这个定时器。after方法返回一个计时器 ID,你可以将其存储在一个变量中,然后在需要时使用after_cancel方法来取消这个定时器。下面是一个例子,展示如何启动和停止一个无限循环的函数:
import tkinter as tk def long_running_function(): while True: # 这里是你的长运行逻辑 print("Running...") root.update_idletasks() root.update() # 创建主窗口 root = tk.Tk() # 保存计时器ID timer_id = None def start_long_running(): global timer_id timer_id = root.after(100, long_running_function) # 每隔100毫秒执行一次 def stop_long_running(): if timer_id is not None: root.after_cancel(timer_id) timer_id = None # 添加按钮用于启动和停止长运行函数 start_button = tk.Button(root, text="Start", command=start_long_running) stop_button = tk.Button(root, text="Stop", command=stop_long_running) start_button.pack() stop_button.pack() root.mainloop()在这个例子中,我们有两个按钮:一个用于启动长运行函数,另一个用于停止它。当点击"Start"按钮时,长运行函数开始执行,每100毫秒更新一次。当点击"Stop"按钮时,我们通过计时器ID取消了定时器,从而停止了长运行函数的执行。
注意:这里使用
root.update_idletasks()和root.update()是为了确保Tkinter事件循环得到更新,以便及时响应用户的操作。在实际应用中,根据你的具体需求,可能需要调整这些调用。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录