J.Barker
J.Barker

Reputation: 51

How can I make a button on tkinter run a function that loops?

I have a specific problem here: I have a button which, when pressed, runs a function that basically consists of a loop.

Here is a simplified version of the code:

from tkinter import *
from tkinter import ttk
root = Tk()

def loop():
    while True:

        print("loop") 

b = Button (root, text = "run", command = loop)
b.grid(row = 1, column = 1)

root.mainloop()

The loop, of course, runs fine. However, as soon as it starts running, the program cannot continue and execute mainloop() again. This means the tkinter window becomes unresponsive. In my actual program, this prevents me from being able to exit the loop and change the function.

So, how can I change the code to make the tkinter window responsive again?

Upvotes: 2

Views: 2500

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

The tkinter method called after() is what you want to use here.

Here is an example of it in action and I have changed the button to toggle a tracking variable to simulate starting and stopping the loop.

The below code will first check if the loop is being accessed by the button and then toggle on or off basically. Then there is a loop built in with the after method to continue the loop until you press the button again.

import tkinter as tk


def loop(toggle=False):
    global tracking_var
    if toggle:
        if tracking_var:
            tracking_var = False
        else:
            tracking_var = True

    if tracking_var:
        print("loop")
        root.after(1000, loop)

root = tk.Tk()
tracking_var = False
tk.Button(root, text="run", command=lambda: loop(True)).pack()

root.mainloop()

Upvotes: 3

Related Questions