tkinter gpio状态问题。。如何让它更新标签以显示最新状态

2024-09-21 03:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

它可以在启动时显示标签,显示gpio 9的原始状态,但单击按钮时不会更改标签文本。我希望它读取gpio的实际状态,而不是按钮被点击的事实。任何帮助都将不胜感激

#tktrial
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
time.sleep(1)
import tkinter as tk
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#setup output pins for relay control

GPIO.setup(9, GPIO.OUT)   #power head 1 ch 4 relay
#setup tkinter
root=tk.Tk()
root.title("trial Aquarium")
root.geometry("800x550")
root.configure(bg="lightblue")
photo1 = tk.PhotoImage(file="fish.gif") #defines a photo and gives the file name
label1 = tk.Label(image=photo1)#puts label in the window in this case not text file must be in program folder
label1.grid(row=10, column=0, columnspan=12) #says how to place the label
#setup fonts
ftlab= 'Verdana', 13, 'bold'
ftb= 'Verdana', 11, 'bold'
#define functions for button     
def pwrhd2on():
    GPIO.output(9, GPIO.HIGH)
def pwrhd2off():
    GPIO.output(9, GPIO.LOW)

state = GPIO.input(9)
if state:
    rt2=('On')
else:
    rt2=('Off')

#setup exit button
Exitbutton= tk.Button(root, text="Exit", font=(ftb), width=6, bg="red", fg="white", command=root.destroy)
Exitbutton.place(x=700, y=240)

#setup powerhead 2 buttons and label
labelpwrhd2= tk.Label(root, text=("POWER HEAD  2"), font=(ftlab), bg="orange", fg="black")
labelpwrhd2.place(x=0, y=496)
butpwrhd2= tk.Button(root, text=("PUMP  ON"), font=(ftb), command=pwrhd2on)
butpwrhd2.place(x=180, y=492)
butpwrhd2= tk.Button(root, text=("PUMP OFF"), font=(ftb), command=pwrhd2off)
butpwrhd2.place(x= 300, y= 492)
labelpwrhd2gpio= tk.Label(root, text=("GPIO          9"), font=(ftlab), bg="black", fg="white")
labelpwrhd2gpio.place(x= 670, y=496)

labelpwrhd2state= tk.Label(root, text=rt2, font=(ftlab), bg="green", fg="black")
labelpwrhd2state.place(x=570, y=496)

root.mainloop()


Tags: textimportoutputgpiosetupplacerootlabel
1条回答
网友
1楼 · 发布于 2024-09-21 03:23:30

在定义函数之前创建标签。使用

def pwrhd2on():
    GPIO.output(9, GPIO.HIGH)
    labelpwrhd2state.configure(text='GPIO 9 On')
def pwrhd2off():
    GPIO.output(9, GPIO.LOW)
    labelpwrhd2state.configure(text='GPIO 9 Off')

除去

state = GPIO.input(9)
if state:
    rt2=('On')
else:
    rt2=('Off')

text=rt2, 希望对你有帮助

相关问题 更多 >

    热门问题