intermittent python thread error, "main thread is not in main loop"

  • Last Update :
  • Techknowledgy :

Your read_temp_raw function is very complicated:

def read_temp_raw():
   with open(device_file) as temp:
   return temp.read().split('\n')

Suggestion : 2

You need to run the GUI code in the main thread, and your temperature reading code needs to be in the background thread. It's only safe to update the GUI in the main thread, so you can pass the temperature data you're reading from the background thread back to the main thread via a Queue, and have the main thread periodically check for data in the queue using self.root.after():,The following program appears to resolve your problem. The call to display in print_it is wrapped in a try block. If it succeeds without an exception, the timer is started to be run later on.,Although those changes alone would avoid the RuntimeError, in theory the GUI could still "freeze" until all the tasks completed because the pool.map() function blocks until all the tasks have completed, which could interfere with tkinter's mainloop() depending on how long that takes. To avoid that I changed pool.map() to pool.async() — which doesn't block because it's unnecessary given the Queue's contents are repeatedly polled.,The reason is that u have used the Threading in the Tkinter loop which I guess we shouldn't. Safe play is to use after. so Custom label can help us in this case

# str8.py
# Program to count time from a certain event

from tkinter
import *
from datetime
import *
from threading
import *

root = Tk()
root.title("STR8")
root.resizable(width = False, height = False)

def main():
   print_it()

def stop():
   root.destroy()

def display():
   event, today, str8, seconds, minutes, hours, days, weeks, years = calc()
Label(root,
   text = "You have been STR8 for:\n",
   font = "Verdana 8 bold").grid(row = 0, sticky = W)
Label(root,
   text = "Years: " +
   str(round(years, 2)),
   font = "Verdana 8").grid(row = 1, sticky = W)
Label(root,
   text = "Weeks: " +
   str(round(weeks, 2)),
   font = "Verdana 8").grid(row = 2, sticky = W)
Label(root,
   text = "Days: " +
   str(round(days, 2)),
   font = "Verdana 8").grid(row = 3, sticky = W)
Label(root,
   text = "Hours: " +
   str(round(hours, 2)),
   font = "Verdana 8").grid(row = 4, sticky = W)
Label(root,
   text = "Minutes: " +
   str(round(minutes, 2)),
   font = "Verdana 8").grid(row = 5, sticky = W)
Label(root,
   text = "Seconds: " +
   str(round(str8.total_seconds())),
   font = "Verdana 8").grid(row = 6, sticky = W)
Button(root,
   text = "EXIT",
   font = "Verdana 8",
   height = 1,
   width = 19,
   command = stop).grid(row = 7)

def calc():
   event = datetime(2017, 3, 29, 13, 45, 0)
today = datetime.now()

str8 = today - event

seconds = str8.total_seconds()
minutes = str8.total_seconds() / 60
hours = minutes / 60
days = hours / 24
weeks = days / 7
years = weeks / 52

return event, today, str8, seconds, minutes, hours, days, weeks, years

def print_it():
   t = Timer(1.0, print_it)
calc()
try:
display()
except RuntimeError:
   pass
else:
   t.start()

main()
root.mainloop()
import tkinter as tk
from pynput
import keyboard

names = ['documents', 'research', 'I forgot the other buttons', 'button 4', 'button 5']
currentBtn = 0

def mkBtn(names):
   for i in range(len(names)):
   globals()[names[i]] = tk.Button(frame, justify = 'left', font = 'Unifont', bd = 0, bg = 'black', activebackground = 'white', text = str(names[i]), relief = 'flat', activeforeground = 'black', foreground = 'white', width = 200)
globals()[names[i]].grid(row = i, column = 0, sticky = 'W')

def on_press(key):
   if key == keyboard.Key.esc:
   return False # stop listener
try:
k = key.char # single - char keys
except:
   k = key.name # other keys
if k in ['up', 'down', 'enter']: # keys of interest
global currentBtn
if k == 'up'
and currentBtn != 0:
   globals()[names[currentBtn - 1]]['state'] = 'active'
globals()[names[currentBtn]]['state'] = 'normal'
currentBtn -= 1

elif k == 'down'
and currentBtn != len(names) - 1:
   globals()[names[currentBtn + 1]]['state'] = 'active'
globals()[names[currentBtn]]['state'] = 'normal'
currentBtn += 1

else:
   print('works')
print(k)

root = tk.Tk()

root.attributes("-fullscreen", True)
root.title("Test")
root.geometry('1920x1080')
root.configure(bg = 'black')

canvas = tk.Canvas(root, width = 1920, height = 1080, bd = '-2', bg = 'black')
canvas.pack()

canvas.create_rectangle(71, 40, 1849, 1040, outline = 'white', fill = 'black', width = 4)

#main menu frame
frame = tk.Frame(root, bg = 'black');
frame.place(relx = .045, rely = .05, relwidth = .909, relheight = .9)

#labeling main menu
mkBtn(names)
documents['state'] = 'active'
listener = keyboard.Listener(on_press = on_press)

listener.start()

root.mainloop()
from tkinter
import *
import threading, time
import sys
root = Tk()
class Custom(Label):
   def __init__(self, parent, lst):
   super().__init__(parent)
self['text'] = lst[0]
self.marker = 0
self.lst = lst[: ]
self.note = len(lst)
self.after(250, self.change)
def change(self):
   if self.marker >= self.note: self.marker = 0
self['text'] = self.lst[self.marker]
self.marker += 1
self.after(250, self.change)
loadings = ['loading', 'loading.', 'loading..', 'loading...']
loading_label = Custom(root, loadings)
loading_label.pack()
# destroy it whenever u want
root.mainloop()
    pushButton.clicked.connect(lambda: self.label.setText(str(datetime.datetime.now())))
public void pauseThread() {
   gameLoop.setKeepPlaying(false);
}

Suggestion : 3

Have you tried messing around with some anycodings_intermittent variation of the following,Edited below to show the function in the anycodings_heroku code where the exception occurs:,I have deployed a Dash-Plotly Python anycodings_heroku application to Heroku using Heroku's "heroku anycodings_heroku git CLI" option. I followed Heroku's anycodings_heroku instructions and the deployment itself was anycodings_heroku uneventful. In fact, the app works like its anycodings_heroku supposed to 75% of the time. (Also note anycodings_heroku that the app works perfectly when run anycodings_heroku locally.),Note that the logs above are for an example anycodings_heroku of the 'freq-low' variable causing a anycodings_heroku KeyError but the error will occur with other anycodings_heroku variables too. Its not simply limited to anycodings_heroku the code around the 'freq-low' variable.

When I dug into the logs, I see the anycodings_heroku following output after a button press:

2021 - 10 - 15 T19: 25: 17.768450 + 00: 00 app[web .1]: Exception on / _dash - update - component[POST]
2021 - 10 - 15 T19: 25: 17.768474 + 00: 00 app[web .1]: Traceback(most recent call last):
   2021 - 10 - 15 T19: 25: 17.768475 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
2021 - 10 - 15 T19: 25: 17.768475 + 00: 00 app[web .1]: response = self.full_dispatch_request()
2021 - 10 - 15 T19: 25: 17.768476 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
2021 - 10 - 15 T19: 25: 17.768476 + 00: 00 app[web .1]: rv = self.handle_user_exception(e)
2021 - 10 - 15 T19: 25: 17.768476 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
2021 - 10 - 15 T19: 25: 17.768477 + 00: 00 app[web .1]: rv = self.dispatch_request()
2021 - 10 - 15 T19: 25: 17.768477 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
2021 - 10 - 15 T19: 25: 17.768477 + 00: 00 app[web .1]: return self.ensure_sync(self.view_functions[rule.endpoint])( ** req.view_args)
2021 - 10 - 15 T19: 25: 17.768478 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/dash/dash.py", line 1096, in dispatch
2021 - 10 - 15 T19: 25: 17.768478 + 00: 00 app[web .1]: response.set_data(func( * args, outputs_list = outputs_list))
2021 - 10 - 15 T19: 25: 17.768478 + 00: 00 app[web .1]: File "/app/.heroku/python/lib/python3.9/site-packages/dash/dash.py", line 1017, in add_context
2021 - 10 - 15 T19: 25: 17.768479 + 00: 00 app[web .1]: output_value = func( * args, ** kwargs) # % % callback invoked % %
   2021 - 10 - 15 T19: 25: 17.768479 + 00: 00 app[web .1]: File "/app/productsearch.py", line 1329, in table_interact
2021 - 10 - 15 T19: 25: 17.768480 + 00: 00 app[web .1]: products = search_products(classname, inputs)
2021 - 10 - 15 T19: 25: 17.768480 + 00: 00 app[web .1]: File "/app/productsearch.py", line 943, in search_products
2021 - 10 - 15 T19: 25: 17.768480 + 00: 00 app[web .1]: elif(low == None or(product['freq-low'] <= low and high <= product['freq-high'])):
   2021 - 10 - 15 T19: 25: 17.768481 + 00: 00 app[web .1]: KeyError: 'freq-low'

Edited below to show the function in the anycodings_heroku code where the exception occurs:

def search_products(class_name, inputs):
   ''
'
This
function is used to create a list of products that meet the search
criteria(product type "class_name"
   and user "inputs").

Parameters:
   inputs: list of Float64 values
input list of Float64 values from user inputs
class_name: string
input string referencing the product class type(i.e "B"
   for Balun)
Returns:
   lists of dicts
list of dicts with product data from the productspec.xls sheet ''
'
if class_name == M:
   low_rf, high_rf, low_lo, high_lo, low_if, high_if, low_lodr, high_lodr = inputs
else:
   low, high = inputs

data = []

for product in class_name.products.values():
   if class_name == M:
   if (
      (low_rf == None or(product['rf-low'] <= low_rf and high_rf <= product['rf-high'])) and(low_lo == None or(product['lo-low'] <= low_lo and high_lo <= product['lo-high'])) and(low_if == None or(product['if-low'] <= low_if and high_if <= product['if-high'])) and(low_lodr == None or(product['lodr-low'] <= low_lodr and high_lodr <= product['lodr-high']))
   ):
      data.append(product)
elif(low == None or(product['freq-low'] <= low and high <= product['freq-high'])):
   data.append(product)

return data

Have you tried messing around with some anycodings_intermittent variation of the following

from dash.exceptions
import PreventUpdate

   ...

   def search_products(class_name, inputs):
   if not class_name and not inputs:
   raise PreventUpdate