2016-08-18 77 views
4

当我运行我的tkinter代码来测量Adafruit的温度。当我运行我的代码时,tkinter会打开一个窗口,但窗口上不会显示任何内容。我之前使用过tkinter,而且我已经有了应该出现的东西,但不是在这个特定的代码中。运行时Tkinter窗口空白

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

为了阐明在READ中的打印行确实运行了30秒。

回答

4

这是因为您没有将它打包在窗口中,而是将它打印在python shell中。

你应该替换print newtext有:

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

工作的代码应该是这样的:

#!/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 label tutorial 和了解更多关于Tkinter的本身,如果你想在标签被覆盖每次它被刷新,你应该使用destroy()方法删除,然后更换标签访问该introduction to tkinter

像这样:

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

这是非常有用的,但你有任何想法如何使它取代温度和湿度线?这就是为什么我在我的代码中有k.set,但结果只是连续打印越来越多的行。 –