【发布时间】:2021-07-16 18:17:24
【问题描述】:
目前我正在处理我的一个涉及传感器的项目,并通过 TKinter 在显示器上显示该感官数据。一切都是用 Python 3.7.3 编写的。
我当前处理的问题是在主循环运行时更新窗口中的标签。 我的意思是,如果我执行脚本,首先定义窗口选项,然后使用 while true 循环定义更新函数。然后它应该启动窗口。现在由于 while true 循环,它没有到达 window.mainloop() 点(显然,while 循环没有中断......)。我的兴趣达到了顶峰,我试图将 window.mainloop() 函数放在更新的 while 循环中(请不要怪我,我知道我的脚本是一团意大利面条。)我发现我可以运行整个线程中的东西,所以我决定线程化整个窗口进程,并为传感器数据添加队列。现在while循环仍然在路上并且没有正常工作,经过一番谷歌搜索后,我发现了一个可能对我有帮助的代码sn-p。在尝试在我的脚本中实现它之后,我得到了一个异常“函数 init 需要 3 个参数,但给出了 4 个参数。”(下面的代码)我有点想不通了。
请记住,我不是真正的开发人员,我只需要一个可以处理传感器数据、在窗口中显示并将当前数据导出到数据库的脚本。所以请放轻松。
当前脚本:
import time
import board
import adafruit_dht
import threading
import queue
from tkinter import *
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
tempQ = queue.Queue(maxsize=0)
humQ = queue.Queue(maxsize=0)
class windowMain:
def __init__(self):
self.tempC_label = Label(fenster, text="Placeholder TempC")
self.humidity_label = Label(fenster, text="Placeholder Humidity")
self.tempC_label.pack()
self.humidity_label.pack()
self.tempC_label.after(2000, self.labelUpdate)
self.humidity_label.after(2000, self.labelUpdate)
def labelUpdate(self, tempQ, humQ):
self.tempC_label.configure(text= tempQ.get() + "°C")
#this is just to confirm if the function called or not, to see if the label updated or not.
#if the label didnt update, and the function called, there is something wrong with the function
#if the label didnt update, and the function didnt call, there is a problem somwhere else
print("Current Temp: " +tempQ.get() + "°C")
self.label.after(2000, self.labelUpdate)
if __name__ == "__main__":
windowName = Tk()
windowName.title = ("Climatemonitor")
windowMain(windowName)
windowName.mainloop()
try:
windowThread = threading.Thread(target=windowMain, args=(tempQ, humQ, ))
windowThread.start()
except:
print("Unable to start thread")
while True:
try:
temperature_c= dhtDevice.temperature
tempText= temperature_c
tempText= str(tempText)
tempQ.put(tempText)
humidity = dhtDevice.humidity
humidityP = str(humidity)
#this one is just to check if the sensor reads data
print(
"Temp: {:.1f} C Humidity: {}% ".format(
temperature_c, humidity
)
)
time.sleep(2.0)
except RuntimeError as error:
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(2.0)
最终目标是显示我的传感器数据,刷新 2 秒(传感器的 HZ 速率),同时传感器每 2 秒继续读取一次。 我还想补充一点,这是我第一次使用 Python,因为我还不是真正的开发人员。 提前感谢大家的每一个批评和帮助
【问题讨论】:
-
最简单的方法是使用一个按钮来执行一个函数,然后在该函数中包含你的while循环。
标签: python loops tkinter window