我想创建一个计时器,当用户按下按钮时从0开始,并在用户再次按下按钮时停止显示。到目前为止,用户after
的所有问题都会查看当前时间,并在几秒钟内从更新的时间更新:
def timer(self):
now = time.strftime("%H:%M:%S")
self.label.configure(text=now)
self.after(1000, self.timer)
但我想从零开始,显示分钟和秒。反正有没有实现这个目标?
答案 0 :(得分:2)
这是一个简单的秒表GUI。还有一些改进空间。 ;)
import tkinter as tk
from time import time
class Stopwatch:
def __init__(self):
root = tk.Tk()
root.title('Stopwatch')
self.display = tk.Label(root, text='00:00', width=20)
self.display.pack()
self.button = tk.Button(root, text='Start', command=self.toggle)
self.button.pack()
self.paused = True
root.mainloop()
def toggle(self):
if self.paused:
self.paused = False
self.button.config(text='Stop')
self.oldtime = time()
self.run_timer()
else:
self.paused = True
self.oldtime = time()
self.button.config(text='Start')
def run_timer(self):
if self.paused:
return
delta = int(time() - self.oldtime)
timestr = '{:02}:{:02}'.format(*divmod(delta, 60))
self.display.config(text=timestr)
self.display.after(1000, self.run_timer)
Stopwatch()
toggle
方法可以打开或关闭秒表。 run_timer
方法使用自计时器启动以来的时间更新display
标签,以分钟为单位。秒。为了更准确,请将.after
延迟减少到500或100.这将对Label执行不必要的(和不可见的)更新,但显示的时间会更准确一些,并且GUI会感觉到反应灵敏。
答案 1 :(得分:1)
import tkinter as tk
import time
class GUI:
def __init__(self, master):
self.root = master
self.parent = tk.Frame(self.root)
self.parent.pack(fill = tk.BOTH)
self.parent.config(bg = "black")
self.now = time.time()
self.buttonVar = tk.IntVar()
self.buttonCycle = False
self.buttonVar.set(0)
self.button = tk.Button(root,
textvariable = self.buttonVar,
command = self.updateButton)
self.button.pack(fill = tk.BOTH)
self.button_cycle()
def updateButton(self):
if self.buttonCycle:
self.buttonCycle = False
self.now = time.time()
elif not self.buttonCycle:
self.buttonCycle = True
def button_cycle(self):
if self.buttonCycle:
now = time.time()
timeDifference = int(now - self.now)
self.buttonVar.set(timeDifference)
self.root.after(1000, self.button_cycle)
root = tk.Tk()
myApp = GUI(root)
root.mainloop()