Oct-01-2021, 05:00 PM
I miss read the requirements, I thought you wanted a button toggle on and off a continuously
Here is some shorter code hopefully more in line with what you asked for.
Note: if the
[Tkinter] How to deal with code that blocks the mainloop, freezing the gui
Here is some shorter code hopefully more in line with what you asked for.
Note: if the
loop_function
does anything that takes too long it will block the GUI event loop see the following[Tkinter] How to deal with code that blocks the mainloop, freezing the gui
import tkinter as tk def loop_function(): print("looping") class MainFrame(tk.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) self._looping = False button1 = tk.Button(self, text="Button1", command=self._on_button1) button1.pack(padx=5, pady=5) self._timer() def _on_button1(self): self._looping = not self._looping def _timer(self): if self._looping: loop_function() self.after(100, self._timer) def main(): app = tk.Tk() mainframe = MainFrame(app) mainframe.pack() app.mainloop() if __name__ == "__main__": main()