Tkinter window is empty at startup

When I run my tkinter code to measure temperature with Adafruit. When I run my code, tkinter opens a window, but nothing appears in the window. I used tkinter before, and I had what should 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, it runs every 30 seconds as intended.

+4
source share
1 answer

this is because you are not wrapping it in a window, but printing it in a python shell.

you should replace this print newtextwith:

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

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()

, , . , tkinter tkinter, tkinter

, , , destroy() , :

#!/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()
+4

Source: https://habr.com/ru/post/1651711/


All Articles