我只是在学习python并跳入课堂。我一直在使用以下代码来找到一个简单的秒表。我现在想用这段代码创建一个类。我任何时候都会在屏幕上有1-4个计时器。我需要同时启动它们,但是独立地结束每个计时器。我仍然不知道这一点,但任何帮助将不胜感激。
import Tkinter as tk
def update_timeText():
if (state):
global timer
timer[2] += 1
if (timer[2] >= 100):
timer[2] = 0
timer[1] += 1
if (timer[1] >= 60):
timer[0] += 1
timer[1] = 0
timeString = pattern.format(timer[0], timer[1], timer[2])
timeText.configure(text=timeString)
root.after(10, update_timeText)
def start():
global state
state = True
def pause():
global state
state = False
def reset():
global timer
timer = [0, 0, 0]
timeText.configure(text='00:00:00')
def exist():
root.destroy()
state = False
root = tk.Tk()
root.wm_title('Simple Kitchen Timer Example')
timer = [0, 0, 0]
pattern = '{0:02d}:{1:02d}:{2:02d}'
timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 150))
timeText.pack()
startButton = tk.Button(root, text='Start', command=start)
startButton.pack()
pauseButton = tk.Button(root, text='Pause', command=pause)
pauseButton.pack()
resetButton = tk.Button(root, text='Reset', command=reset)
resetButton.pack()
quitButton = tk.Button(root, text='Quit', command=exist)
quitButton.pack()
答案 0 :(得分:0)
要创建一个类,只需尝试:
import Tkinter as tk
class StopWatch(object): # sub-class the object class maybe
def update_timeText(self):
#your code logic...
def start(self):
#your code logic...
#etc...
#the rest of your functions are the same
#just specify the 'self' Python keyword before any other arguments in the function. :D
如果有效,请告诉我。 :D
答案 1 :(得分:0)
这是我的解决方案。我花了这么长时间才开始围绕这个课堂创作。有什么改进的想法吗?
import Tkinter as tk
root = tk.Tk()
root.wm_title('Stopwatch Class')
root.geometry("300x350")
class StopWatch(object):
def __init__(self):
self.pattern = '{0:02d}:{1:02d}:{2:02d}'
self.timer = [0, 0, 0]
self.state = False
self.timeText = tk.Label(root, text='00:00:01', font=("Helvetica", 15))
self.timeText.pack()
self.startButton = tk.Button(root, text='Start', command=self.start)
self.startButton.pack()
self.resetButton = tk.Button(root, text='Reset', command=self.reset)
self.resetButton.pack()
self.pauseButton = tk.Button(root, text='Pause', command=self.pause)
self.pauseButton.pack()
def update_timeText(self):
if (self.state):
self.timer[2] += 1
if (self.timer[2] >= 100):
self.timer[2] = 0
self.timer[1] += 1
if (self.timer[1] >= 60):
self.timer[0] += 1
self.timer[1] = 0
self.timeString = self.pattern.format(self.timer[0], self.timer[1], self.timer[2])
self.timeText.configure(text=self.timeString)
root.after(10, self.update_timeText)
def start(self):
self.state = True
def pause(self):
self.state = False
def reset(self):
self.timer = [0, 0, 0]
self.timeText.configure(text='00:00:00')
# create a new stopwatch
swatch1 = StopWatch()
swatch1.update_timeText()
# create a new stopwatch
swatch2 = StopWatch()
swatch2.update_timeText()
# create a new stopwatch
swatch3 = StopWatch()
swatch3.update_timeText()
root.mainloop()