【发布时间】:2018-06-11 14:35:06
【问题描述】:
此代码是模拟智能烤面包机的程序的开始。我正在尝试为我的倒数计时器制作一个取消按钮。定时器工作正常,除了当按下取消按钮时,显示消息“定时器完成”,但定时器继续。有什么办法可以做到吗?
from tkinter import *
import time
class Window(Frame): #creating window
def __init__(self, master = None): #defining master window
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("GUI")
self.pack(fill=BOTH, expand=1) #allowing size of window to be changed during running of program
#using a slider instead of a dial as no dial in tkinter
timerinputDial = Scale(self, from_=0, to=6, tickinterval=1, showvalue=0)
timerinputDial.place(x=200, y=20)
#Timer
def count_down():
for t in range(((timerinputDial.get())*60), -1, -1): #starts with the value of the input dial
# format as 2 digit integers, fills with zero to the left
# divmod() gives minutes, seconds
sf = "{:02d}:{:02d}".format(*divmod(t, 60))
#print(sf)
time_str.set(sf)
root.update()
# delay one second
time.sleep(1)
if t == 0:
time_str.set(timer_done) #telling user timer is finished
timerinputDial.set(0) #setting dial back to 0
return
def cancel():
time_str.set(timer_done) #telling user timer is finished
timerinputDial.set(0) #setting dial back to 0
return
time_str = StringVar()
timer_done = "Timer done"
# creating the time display label, giving it a large font
# labelling auto-adjusts to the font
label_font = ('helvetica', 40)
Label(root, textvariable=time_str, font=label_font, bg='white',
fg='blue', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
# creating start and stop buttons
# pack() positions the buttons below the label
startButton = Button(root, text='Start', command=count_down).pack()
# stop simply exits root window
cancelButton = Button(root, text='Cancel', command=cancel).pack()
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
【问题讨论】:
-
你应该包含完整的代码。
-
好的。我已经对其进行了编辑以添加更多代码,因此希望它更有意义。
-
计时器实际上是继续还是从 0 重新开始但仍在继续计数?
-
我们不需要完整代码,我们需要一个带有适当缩进的minimal reproducible example。
-
count_down 函数工作正常:它从所需时间开始倒计时并停在零处,但如果我在倒计时期间按下取消按钮,消息 Timer done 会出现一秒钟,然后倒计时从无论取消功能是否已运行,同一点。
标签: python user-interface tkinter timer countdown