问题
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