python - 在 tkinter 中显示传感器读数
问题描述
我已经将流量传感器与树莓派接口。我希望每秒在 tkinter gui 上更新此读数。请帮助我编写代码。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
flowin =7
GPIO.setup(7,GPIO.IN)
rate=0
seconds=0
pulse=550
time_new = 0.0
#numlist=list()
while True:
y=2
time_new = time.time() + 1
rate_cnt = 0
#y=numlist.append(x)
while time.time() <= time_new:
x=GPIO.input(flowin)
if y!=x:
if GPIO.input(flowin)!= 0:
rate+= 1
y=x
seconds+=1
litre=rate/pulse
minutes=seconds/60
flowrate=litre/minutes
#print("flowrate",flowrate)
解决方案
您可以使用thread
读取传感器读数并更新StringVar
与 tkinter 关联的 aLabel
以显示flowrate
.
以下是基于您的代码的示例:
import RPi.GPIO as GPIO
import tkinter as tk
import time
import threading
def read_sensor():
GPIO.setmode(GPIO.BOARD)
flowin =7
GPIO.setup(7,GPIO.IN)
rate=0
seconds=0
pulse=550
time_new = 0.0
#numlist=list()
while True:
y=2
time_new = time.time() + 1
rate_cnt = 0
#y=numlist.append(x)
while time.time() <= time_new:
x=GPIO.input(flowin)
if y!=x:
if GPIO.input(flowin)!= 0:
rate+= 1
y=x
seconds+=1
litre=rate/pulse
minutes=seconds/60
flowrate=litre/minutes
#print("flowrate",flowrate)
# update the tkinter label via StringVar
var.set(f'flowrate: {flowrate:10.2f}')
# create the thread
task = threading.Thread(target=read_sensor, daemon=True)
root = tk.Tk()
var = tk.StringVar()
lbl = tk.Label(root, textvariable=var, width=40, height=5, font=('Consolas', 24, 'bold'))
lbl.pack()
task.start() # start the reading thread
root.mainloop()
推荐阅读
- python - “未能在超时时间内找到 libpython。” 尝试使用 pyflame 分析不在容器中的 .py 文件时
- python - 如何仅基于组的一行来调整 groupby 的更改
- maven - 无法在 Eclipse 中创建 Maven 项目
- apache - 有关于在部署模式下运行 Nutch 2.0 的任何信息吗?
- windows - WebStorm git difftool -d 立即关闭,无需等待用户
- ncache - 安装 ncache.opensource.clr40.x64.msi(版本 4.9 SP1)后缺少命令行工具
- java - org.apache.pdfbox.text.TextPosition 中的坐标单位是什么
- javascript - 在 d3 地图上设置点的初始“默认”不透明度
- python - 使用 python 和烧瓶,如何将动态路由参数传递给 AJAX 请求调用的新路由?
- c - DMA 传输只运行一次