【发布时间】:2023-04-11 03:36:01
【问题描述】:
我的代码有问题,当我按下开始按钮计时器开始工作时 但是停止定时器功能不起作用,如何用停止功能停止定时器? 请帮帮我
这是我的代码:
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 """
hours = int(elap/3600)
minutes = int((elap - hours*3600)/60)
seconds = int(elap - hours*3600-minutes*60)
self.timestr.set('%02d:%02d:%02d' % (hours,minutes, seconds))
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 Run(self):
#self.btnstop.config(text="Start",command=self.Run)
#if self.vs.isOpened() == False:
#self.vs.open(0)
""" Get frame from the video stream and show it in Tkinter """
ok, frame = self.vs.read() # read frame from video stream
self.Start()
if cv2.waitKey() == 27:
self.Stop()
if ok: # frame captured without any errors
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert colors from BGR to RGBA
self.current_image = Img.fromarray(frame) # convert image for PIL
panel = Label(self.canvas_area) # initialize image panel
panel.config(width=500,height=500)
panel.grid(column=0,row=0)
imgtk = ImageTk.PhotoImage(image=self.current_image) # convert image for tkinter
panel.imgtk = imgtk # anchor imgtk so it does not be deleted by garbage-collector
panel.config(image=imgtk) # show the image
self.after(30, self.Run) # call the same function after 30 milliseconds
#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
【问题讨论】:
-
什么是
self.after?如何启动和停止计时器?你的其余代码在哪里? -
你能发布一个最小的可重现示例吗?阅读stackoverflow.com/help/minimal-reproducible-example。
-
我不知道最初调用
Run()是什么,但我发现一旦发生这种情况就没有什么会阻止它的重复执行——它每次运行时都会调用Start()(这将(重新)启动秒表)。 -
在
self.Stop()之后添加一个return -
代替
0,1你可以使用True,False- 它会更易读。
标签: python python-3.x tkinter