X
X
xomiles2021-10-21 16:08:36
Python
xomiles, 2021-10-21 16:08:36

How to solve the problem with threads?

How to fix the error?
The first message gives, the next gives an error

from threading import Thread
from tkinter import messagebox

header_msg = "5555"

def fn(mess_msg, header_msg):
  messagebox.showerror(str(header_msg), str(mess_msg))

while True:
  mess_msg = input(">>>: ")
  th = Thread(target=fn, args=(mess_msg, header_msg))
  th.start()


Mistake

$ python r.py
>>>: afsfs
>>>: dasd
>>>: Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "r.py", line 14, in fn
    messagebox.showerror(str(header_msg), str(mess_msg))
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\tkinter\messagebox.py", line 94, in showerror
    return _show(title, message, ERROR, OK, **options)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\tkinter\messagebox.py", line 72, in _show
    res = Message(**options).show()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\tkinter\commondialog.py", line 40, in show
    w = Frame(self.master)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 3119, in __init__
    Widget.__init__(self, master, 'frame', cnf, {}, extra)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2567, in __init__
    self.tk.call(
RuntimeError: main thread is not in main loop

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-21
@xomiles

Tk, like any other GUI library, is not thread-safe, so GUI components can only be accessed from the main thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question