当我运行我的 tkinter 代码以使用 Adafruit 测量温度时。当我运行我的代码时,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 秒。
最佳答案
这是因为你不是在window中打包而是在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()
方法来删除然后替换标签,如下所示:
#!/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()
关于python - 运行时 Tkinter 窗口为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39026823/