下面是在GUI上创建按钮以控制秒表的代码。 我想问一下是否有人知道如何修改代码,以便我们可以在覆盆子PI上使用GPIO引脚作为输入(意味着我们有3个按钮组件来控制秒表运行)。
我唯一知道的是我们必须将RPi.GPIO作为GPIO,GPIO.setmode(GPIO.BOARD)和GPIO.setup()引入GPIO引脚。 任何人都可以帮助我???
from Tkinter import *
import time
class StopWatch(Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = StringVar()
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
l = Label(self, textvariable=self.timestr)
self._setTime(self._elapsedtime)
l.pack(fill=X, expand=NO, pady=2, padx=2)
def _update(self):
""" Update the label with elapsed time. """
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._timer = self.after(50, self._update)
def _setTime(self, elap):
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))
def Start(self):
""" Start the stopwatch, ignore if running. """
if not self._running:
self._start = time.time() - self._elapsedtime
self._update()
self._running = 1
def Stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._running = 0
def Reset(self):
""" Reset the stopwatch. """
self._start = time.time()
self._elapsedtime = 0.0
self._setTime(self._elapsedtime)
def main():
root = Tk()
sw = StopWatch(root)
sw.pack(side=TOP)
Button(root, text='Start', command=sw.Start).pack(side=LEFT)
Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
Button(root, text='Quit', command=root.quit).pack(side=LEFT)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:2)
Makezine建议使用GPIO an extensive tutorial。
您可以在_update
方法中轮询按钮值。
if self._running and (GPIO.input(23) ==1):
self.Stop()
当你的时钟没有运行时,这将不起作用,所以你可能会调整你的逻辑以使你的_update
后循环始终在运行(或者创建另一个专用于Pi按钮轮询的后循环)。 / p>
此外,GPIO在另一个线程中提供了waitloop。这是对Makezine的例子的改编,以链接回tkinter(未经测试)。
def relayToTkinter(channel):
sw.event_generate('<<Start>>', when='tail')
GPIO.add_event_detect(23, GPIO.RISING, callback=relayToTkinter, bouncetime=300)
sw.bind("<<Start>>", lambda event:sw.Start())
event_generate("<<VirtualEvent>>", when='tail')
是让另一个线程与主UI线程交互的安全方法。