Python Tkinter 使用 Raspberry Pi 更新 GUI

Python Tkinter using Raspberry Pi updating GUI

最近我一直在 Raspberry pi 的 Tkinter 上工作,为家庭自动化构建一个 GUI,我想设计一个验证模块,上面写着 "ACTIVE" 当传感器工作时和 "INACTIVE" 当传感器发生故障时。 我能够在 GUI 中获得验证,但它不是动态的。每次我必须重新运行程序来获取传感器的更新状态

有没有一种方法可以更新 ActiveInactive 状态而无需重新 运行 整个程序?

我正在从 raspberry pi 上的 GPIO 引脚获取输入并在程序中读取它们

这是我目前使用的代码:

import RPi.GPIO as GPIO
import time
from tkinter import *
from tkinter import ttk
import tkinter.font


GPIO.setwarnings(False)


Sig1 = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Sig1, GPIO.IN)

out1 = 11# pin11
GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location
GPIO.setup(out1, GPIO.OUT) # We have set our LED pin mode to output
GPIO.output(out1, GPIO.LOW)

gui = Tk()
gui.title("tkinter")
gui.config(background = "gray86")
gui.minsize(1050,620)

Font1 = tkinter.font.Font(family = 'Courier 10 Pitch', size = 20, weight = 'bold')
Font2 = tkinter.font.Font(family = 'Courier 10 Pitch', size = 18, weight = 'bold')
Font3 = tkinter.font.Font(family = 'Courier 10 Pitch', size = 9, weight = 'bold')

def func1_on():
    GPIO.output(out1, GPIO.HIGH) # led on
    Text1 = Label(gui,text=' ON ', font = Font2, bg = 'gray84', fg='green3', padx = 0)
    Text1.grid(row=8,column=1)

def func1_off():
    GPIO.output(out1, GPIO.LOW) # led off
    Text2 = Label(gui,text='OFF', font = Font2, bg = 'gray84', fg='red', padx = 0)
    Text2.grid(row=8,column=1)

label_2 = Label(gui,text='Sensor:', font = Font2, fg='gray40', bg = 'gray84', padx = 10, pady = 10)
label_2.grid(row=6,column=0)

if GPIO.input(Sig1) == True:
    Text3 = Label(gui,textvariable=' Active ',relief = "raised", font = Font2, bg = 'gray84', fg='green3', padx = 0)
    Text3.grid(row=6,column=1)
else:
    Text4 = Label(gui,textvariable=' Inactive ',relief = "raised", font = Font2, bg = 'gray84', fg='red', padx = 0)
    Text4.grid(row=6,column=1)


Button1 = Button(gui, text='Switch On', font = Font3, command = func1_on, bg='gray74', height = 1, width = 7)
Button1.grid(row=8,column=0)
Button2 = Button(gui, text='Switch Off', font = Font3, command = func1_off, bg='gray74', height = 1, width = 7)
Button2.grid(row=9,column=0)

gui.mainloop()

如果有人能帮助我,我将不胜感激。

定期使用root.after(milliseconds, function_name)运行一些功能。

此函数应检查传感器、更新标签中的文本并在一段时间后再次使用 root.after 到 运行。

顺便说一句:function_name 应该没有 ()


最小的例子。它用当前时间更新标签

import tkinter as tk
import time

# --- functions ---

def check():
    # update text in existing labels
    label['text'] = time.strftime('%H:%M:%S')

    # run again after 1000ms (1s)
    root.after(1000, check) 

# --- main ---

root = tk.Tk()

label = tk.Label(root)
label.pack()

check() # run first time

root.mainloop()