python – 运行时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秒.

解决方法:

这是因为你没有将它打包在窗口中但是你将它打印在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本身的更多信息,请访问此introduction to tkinter

如果你希望每次刷新时都要覆盖标签,你应该使用destroy()方法删除然后像这样替换Label:

#!/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()
上一篇:爬虫(一):东方财富股吧评论


下一篇:ON1 Photo RAW 2021.5 for mac(专业图像处理软件)