python - 在 GUI 中显示 DHT11 的温度 - 自动刷新?

标签 python tkinter

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

我正在使用标准Adafruit DHT11 Library对于Python。

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

最佳答案

在程序开始时创建标签一次,并保存引用:

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。然后它将运行直到您的程序退出。

关于python - 在 GUI 中显示 DHT11 的温度 - 自动刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37667389/

相关文章:

python - 查找 Python 模块文件名

python - 使用 Python 将 HTML 表示形式替换为 ascii

python - Nginx 调试日志记录级别

python - 让 Pynng 和 socket 相互对话

python - 从 Tkinter 标签中删除 {}

python - 有没有办法从 MongoDB 中的 INT 创建 ObjectID?

python - 使用一个类在另一个类中设置参数 - Python

python - 如何使用 Tkinter 按钮从 python 运行 exe

python-3.x - 此 Python 代码中多重继承的最佳实践

python - 如何使用 pack 或 grid 实现以下 Tkinter GUI 布局?