I am creating a program that runs multiple threads where each thread updates a variable and then displays that value using tkinter.
The only problem is that I get a RuntimeError whenever I try and update the display:
Exception in thread Thread-x:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "program.py", line 15, in body
update()
File "program.py", line 11, in update
display.config({"text" : "x = {0}".format(x)})
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure
return self._configure('configure', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
RuntimeError: main thread is not in main loop
Some of the solutions I have tried to fix the error are:
- Make the display object global to the function (using
global) - Create a seperate function to update the display
However, none of these solutions worked (the RuntimeError still kept occurring).
Below is my program:
import tkinter, time, threading
window = tkinter.Tk()
x = 0
display = tkinter.Label(window)
display.pack()
def update():
global x
x += 1
display.config({"text" : "x = {0}".format(x)}) #It says the error is on this line
def body():
time.sleep(3)
update()
body()
def start_threads():
for i in range(5):
thread = threading.Thread(target=body)
thread.start(); thread.join()
start = tkinter.Button(window, text="Start", command=start_threads)
start.pack()
I do not know how to fix the RuntimeError, so any help with that would be appreciated.