Ongoing event in tkinter

痴心易碎 提交于 2021-01-29 05:20:58

问题


Using tkinter, can I bind an ongoing event to activate while the mainloop still goes off? Means it executes the same command over and over until the program is closed


回答1:


you can use root.after to run a function repeatedly like so:

def repeat_task():
    # do stuff
    root.after(10, repeat_task)

this will constantly do something, and then run itself. the delay time shouldn't be 0 because it may not let tkinter's event loop process other events and will freeze. it will go until the window is closed.




回答2:


You can also use threading approach:

import tkinter as tk
import threading

def myLoop():
    print("Hey I am looping!")
    threading.Timer(1, myLoop).start()

window = tk.Tk()
button = tk.Button(window, text = 'Threading', command = lambda: threading.Timer(1, myLoop).start()) 
button.pack()
window.mainloop()
  • threading.Timer is an object that will run parallel to your GUI so it won't freeze it.
  • threading.Timer will fire up every Nth second that you can specify in the constructor.


来源:https://stackoverflow.com/questions/65817918/ongoing-event-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!