tkinter gpio 状态问题.. 我怎样才能让它更新标签以显示最新状态

这可以在启动时显示标签,它显示 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()



哆啦的时光机
浏览 69回答 1
1回答

米琪卡哇伊

在定义函数之前创建标签。利用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, 希望这会有所帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python