How to run multiple threads in tkinter

Viewed 1007

Let's say if we write something like this:

import threading
Button(root, command=threading.Thread(target=func1).start)

Now if we click the button once then it will be fine but we try to click the button again then a error comes "Thread can only be executed once".

So, how to avoid this

2 Answers

Edited Answer:: As you clarified it in comments, you can redefine the Button every time it is clicked allowing it to accept multiple clicks and thus creating multiple threads as required. You could do that inside the target func1() or callback function for threading.Thread object.

A working example example would be like this:

import tkinter as tk
import threading

def func1():
    theButton.configure(command=threading.Thread(target=func1).start)
    print('Do everything else here')

root = tk.Tk()
theButton = tk.Button(root, text='Start', command=threading.Thread(target=func1).start)
theButton.pack()
root.mainloop()

Edit: Thanks to CoolCloud for suggesting a better way to configure the Button inside callback func1().

It is because you create one instance of threading.Thread() and pass its start method to command option of the button. You should create new instance whenever the button is clicked by using lambda:

import tkinter as tk
import threading

root = tk.Tk()

def func1():
    print('Hello')

tk.Button(root, text='Go', command=lambda: threading.Thread(target=func1).start()).pack()

root.mainloop()
Related