Search code examples
pythontkinterraspberry-pirefreshadafruit

Tkinter window is blank when running


When I run my tkinter code for measuring the temperature with Adafruit. When I run my code tkinter opens a window but nothing appears on the window. I have used tkinter a bit before and I have had what is supposed to appear appear but just not in this particular code.

#!/usr/bin/python
# -*- coding: latin-1 -*-

import Adafruit_DHT as dht
import time
from Tkinter import *

root = Tk()
k= StringVar()
num = 1
thelabel = Label(root, textvariable=k)
thelabel.pack

def READ():
    h,t = dht.read_retry(dht.DHT22, 4)
    newtext = "Temp=%s*C Humidity=%s" %(t,h)
    k.set(str(newtext))
    print newtext #I added this line to make sure that newtext actually had the values I wanted

def read30seconds():
    READ()
    root.after(30000, read30seconds)

read30seconds()
root.mainloop()

And to clarify the print line in READ does run ever 30 seconds as intended.


Solution

  • it is because you are not packing it in the window but you are printing it in the python shell.

    you should replace that print newtext with:

    w = Label(root, text=newtext)
    w.pack() 
    

    a working code should look like this:

    #!/usr/bin/python
    # -*- coding: latin-1 -*-
    
    import Adafruit_DHT as dht
    import time
    from Tkinter import *
    
    root = Tk()
    k= StringVar()
    num = 1
    thelabel = Label(root, textvariable=k)
    thelabel.pack
    
    def READ():
        h,t = dht.read_retry(dht.DHT22, 4)
        newtext = "Temp=%s*C Humidity=%s" %(t,h)
        k.set(str(newtext))
        w = Label(root, text=newtext)
        w.pack() 
    
    
    def read30seconds():
        READ()
        root.after(30000, read30seconds)
    
    read30seconds()
    root.mainloop()
    

    note that this is a very basic code graphically speaking. to learn more about this topic visit this tkinter label tutorial and to learn more about tkinter itself visit this introduction to tkinter

    if you want the label to be overwritten everytime it is refreshed you should use the destroy() method to delete and then replace the Label like this:

    #!/usr/bin/python
    # -*- coding: latin-1 -*-
    
    import Adafruit_DHT as dht
    import time
    from Tkinter import *
    
    root = Tk()
    k= StringVar()
    num = 1
    thelabel = Label(root, textvariable=k)
    thelabel.pack
    
    def READ():
        global w
        h,t = dht.read_retry(dht.DHT22, 4)
        newtext = "Temp=%s*C Humidity=%s" %(t,h)
        k.set(str(newtext))
        print newtext #I added this line to make sure that newtext actually had the values I wanted
    
    def read30seconds():
        READ()
        try: w.destroy()
        except: pass
        root.after(30000, read30seconds)
    
    read30seconds()
    root.mainloop()