Python Forum

Full Version: Problem reading entry box in thread
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good Morning,

I am new to Python. I am trying to build a program that reads a temperature from an Entry widget once every second and performs an action based upon what that temperature is. I set up a thread to do this - but it does not like the statement where I read the value of that entry widget. If I run it outside of a thread, it works, but I do not get my GUI interface to show up (hence the use of a thread). Code is below:

#!/usr/bin/env python
from tkinter import *
from tkinter import ttk
import threading
import time

def theThread():
	global lvgTemp
	global stgUp
	global stgDn
	global stgOff
	while (True):
		s= float(lvgTemp.get())
		if ( s > 52.0 ):
			stgUp = True
		else:
			if ( s < 45.0 ):
				stgDn = True
		
		if ( s < 35.0 ):
			stgOff = True
		
		print('Stage Up: ', stgUp, ' Stage Down: ', stgDn, ' Comp Off: ', stgOff)
		time.sleep(1)

stgUp = False
stgDn = False
stgOff= False
root = Tk()
root.geometry('640x480+200+200')


lvgTmp1=ttk.Label(root, text="52.0 F")
lvgTmp1.place(x=50, y=100)
lvgTmp2=ttk.Label(root, text="45.0 F")
lvgTmp2.place(x=100, y=100)
lvgTmp3=ttk.Label(root, text="35.0 F")
lvgTmp3.place(x=150, y=100)

v = StringVar(root, value='50.0')
lvgTemp = ttk.Entry(root, textvariable=v)
lvgTemp.place(x=50, y=150)

t=threading.Thread(target=theThread)
t.start()
Thanks,
Lee
It is not a good idea to start with tkinter by using threads. Instead of a thread, you can use itkinter's after() method to call a function after a certain delay, for example root.after(1000, myfunc) will call myfunc after 1000 milliseconds. Instead of a while True loop, use repeated calls to after().

Last, but not least, if you want to see the GUI, you need to start the root.mainloop().
Thanks so much for your help - yes, I found that I was missing the root.mainloop().

Also, I will look into using .after

Again - Thanks!!!

Lee...