这个Python和GUI东西(tkinter)刚好陌生,已经进行了大约3天的工作,并且用光了我的资源,我要做的就是单击“开始”按钮并使我的螺线管打开并运行,然后单击“停止”使其停止...
import RPi.GPIO as GPIO
import time
from tkinter import *
import tkinter.font as font
root = Tk()
root.geometry('500x500') #size of window
class Cycle:
def __init__(self, master):
frame = Frame(master)
frame.pack()
myFont = font.Font(size=20) #define Font
self.printButton = Button(frame, text="Start", bg="green", fg="black", command = self.printMessage,width=20, height=5)
self.printButton['font'] = myFont
self.printButton.pack()
self.quitButton = Button(frame, text ="Stop", bg="red", fg="black", command =frame.quit, width=20, height=5)
self.quitButton['font'] = myFont
self.quitButton.pack()
def printMessage(self):
print("Well Done!!!")
root.mainloop()
channel = 21
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.OUT)
def solenoid_on(pin):
GPIO.output(pin, GPIO.HIGH) # Turn solenoid on
def solenoid_off(pin):
GPIO.output(pin, GPIO.LOW) # Turn solenoid off
if __name__ == '__main__':
try:
for i in range(2): # Number of times ran is writen in ==> [range(put run times here)]
solenoid_on(channel)
time.sleep(1) # Sets lag time
solenoid_off(channel)
time.sleep(1) # Sets run time
print("Cycles", i+1)
GPIO.cleanup()
except KeyboardInterrupt:
GPIO.cleanup()
答案 0 :(得分:1)
将两个按钮的回调更改为正确的功能。
self.printButton = Button(frame,
text="Start",
bg="green",
fg="black",
command=lambda: solenoid_on(21),
width=20,
height=5)
和
self.printButton = Button(frame,
text="Start",
bg="red",
fg="black",
command=lambda: solenoid_off(21),
width=20,
height=5)
然后使用
实例化Cycle
c = Cycle(root)
在开始事件循环之前。