【问题标题】:Displaying Temperature from DHT11 in GUI - Automatic Refresh?在 GUI 中显示 DHT11 的温度 - 自动刷新?
【发布时间】:2016-06-06 21:48:05
【问题描述】:

Python 新手,开始使用 DHT11 温度/湿度传感器、Raspberry Pi 3 和 Python 3。

我使用 Python 的标准 Adafruit DHT11 Library

从 GPIO 27 读取

我能够在 GUI 窗口中显示温度就好了。我坚持的是如何让 GUI 以设定的速率更新/刷新温度,因此它是当前温度的“实时”显示。现在,如果我关闭并重新打开我的脚本,我只能从 GUI 获得更改。请参阅下面的代码:

    from tkinter import *
    import tkinter.font
    import Adafruit_DHT

    temp = 0

    win = Tk()
    win.title("Temperature")
    win.geometry("100x100")

    def READ():
        global temp
        humidity, temperature = Adafruit_DHT.read_retry(11, 27)
        temp = temperature * 9/5.0 + 32
        Label (win, text=str(temp), fg="black", bg="white", font="36").grid(row=0, column=0)

    if (temp >= 0):
        READ()

    mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    在程序启动时创建一次Label,并保存引用:

    the_label = Label (win, text="", fg="black", bg="white", font="36")
    the_label.grid(row=0, column=0)
    

    接下来,创建一个获取值并更新标签的函数:

    def READ():
        global temp
        humidity, temperature = Adafruit_DHT.read_retry(11, 27)
        temp = temperature * 9/5.0 + 32
        the_label.configure(text=str(temp))
    

    接下来,创建一个调用这个函数的新函数,然后安排自己在延迟后再次被调用:

    def read_every_second():
        READ()
        root.after(1000, read_every_second)
    

    最后,在程序开始时调用一次read_every_second。然后它将一直运行,直到您的程序退出。

    【讨论】:

    • 谢谢!效果很好,我现在对函数调用有了更好的理解!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多