0

I'm working on a GUI for a simulation software and need to have two processes running at the same time. One for the simulation, and one for displaying information for the user. BOTH threads need to make changes to the GUI. When I run my code, I get the error: RuntimeError: main thread is not in main loop.

After some research, I think that there is no way you can access the GUI from a different thread than the main thread. I also think that I probably should use Queues, but I am not sure how to do this. Here's my simplified code:

import tkinter as tk
from tkinter import END
import threading
import time


def write_to_entry1():
    for i in range(20):
        entry1.delete(0, END)
        entry1.insert(0, i)
        entry1.update()
        time.sleep(1)


def write_to_entry2():
    for i in range(20):
        entry2.delete(0, END)
        entry2.insert(0, i)
        entry2.update()
        time.sleep(1)


# Creating the GUI
root = tk.Tk()
root.geometry("200x100")
label1 = tk.Label(root)
label1.configure(text="Thread 1:")
label1.grid(column='0', row='0')
entry1 = tk.Entry(root)
entry1.grid(column='1', row='0')
label2 = tk.Label(root)
label2.configure(text="Thread 2:")
label2.grid(column='0', row='1')
entry2 = tk.Entry(root)
entry2.grid(column='1', row='1')
root.update()

t = threading.Thread(target=write_to_entry2)
t.daemon = True
t.start()

write_to_entry1()

root.mainloop()

Thanks for any answers.

  • See my answer to this [question](https://stackoverflow.com/questions/59327160/what-techniques-are-there-to-allow-multiple-threads-in-a-tkinter-program) – quamrana Feb 18 '22 at 20:49
  • 1
    [My answer](https://stackoverflow.com/a/53697547/355230) to [Freezing/Hanging tkinter GUI in waiting for the thread to complete](https://stackoverflow.com/questions/53696888/freezing-hanging-tkinter-gui-in-waiting-for-the-thread-to-complete) shows how to use a `Queue` in a multithreaded tkinter application. Since you control what's goes into it and what happens when items are removed from it, you should be able to do what you want. Note @quamrana's answer is very similar to mine. – martineau Feb 18 '22 at 20:51

0 Answers0