0

我对 Python 和 tkinter 很陌生,但我有一个基本的 GUI,它只显示从 GPIO 读取的温度。我唯一不能上班的是温度没有更新。

如果有人可以提供帮助,那就太好了。

谢谢。

#!/usr/bin/env python3

from tkinter import *
from tkinter import ttk
from tkinter import font
import time
import glob
import os

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def quit(*args):
    root.destroy()

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.after(0.1)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = round(float(temp_string) / 1000.0,3)
        return temp_c
    root.after(1000, read_temp) 

root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
root.bind("<Escape>", quit)
root.bind("x", quit)

fnt = font.Font(family='Helvetica', size=300, weight='bold')
txt = StringVar()
txt.set(read_temp())
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="white", background="black")
lbl.place(relx=0.5, rely=0.5, anchor=CENTER)

root.after(1000, read_temp)

root.mainloop()
4

1 回答 1

0

为了lbl使用温度读数更新温度标签并根据温度设置其颜色,您需要:

ttk.Label1.为颜色创建样式(如您所用)

style = ttk.Style()
style.configure('Blue.TLabel',  foreground='blue')
style.configure('Green.TLabel', foreground='green')
style.configure('Red.TLabel',   foreground='red')

在创建温度标签之前放置代码块

2.删除foreground初始化温度标签时的设置

lbl = ttk.Label(root, textvariable=txt, font=fnt, background="black")

3.更新里面的温度标签read_temp()

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.after(0.1)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = round(float(temp_string) / 1000.0,3)
        # update temperature label
        txt.set(f'{temp_c:.3f} °C')
        # set its color based on temperature reading
        style = 'Blue.TLabel' if temp_c < 23 else 'Red.TLabel' if temp_c > 28 else 'Green.TLabel'
        lbl.config(style=style)
    root.after(1000, read_temp) 
于 2019-07-24T01:49:52.570 回答