Tkinter闹钟

时间:2016-06-25 21:59:12

标签: python-3.x tkinter

我正在尝试使用tkinter构建一个倒数计时器。我想将条目中的值传递给倒计时(count)函数。这是我试过的:

def countdown(count): 
    label['text'] = count

    if count > 0:
        top.after(1000, countdown,count-1)

top = tkinter.Tk()
top.geometry("700x100")
hoursT=tkinter.Label(top, text="Hours:")
hoursE=tkinter.Entry(top)
minuteT=tkinter.Label(top, text="Minutes:")
minuteE=tkinter.Entry(top)
secondT=tkinter.Label(top, text="Seconds:")
secondE=tkinter.Entry(top)
hoursT.grid(row=1,column=1)
hoursE.grid(row=1,column=2)
minuteT.grid(row=1,column=3)
minuteE.grid(row=1,column=4)
secondT.grid(row=1,column=5)
secondE.grid(row=1,column=6)
label = tkinter.Label(top)
label.grid(row=3)

t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get())
button=tkinter.Button(top,text="Start Timer",command=lambda        count=t:countdown(count))
button.grid(row=2)

然而,我收到此错误:

Traceback (most recent call last):
File "C:\Users\charley.ACER-PC\AppData\Local\Programs\Python\Python35-    32\tkinterTutorial.py", line 30, in <module>
t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get()))
ValueError: invalid literal for int() with base 10: ''

如何运行此代码:

t=(int(hoursE.get())*360+int(minuteT.get())*60+int(secondE.get())

只有当条目用整数填充时才会出现?

谢谢:)

1 个答案:

答案 0 :(得分:0)

一种解决方案是首先将按钮放在那里,change the command在运行时使用event listeners

button=tkinter.Button(top,text="Start Timer",command=lambda:None)
button.grid(row=2)

def updateButton():
    hour,min,sec=hoursE.get(),minuteT.get(),secondE.get()
    if hour.isdigit() and min.isdigit() and sec.isdigit():
        time=int(hour)*360+int(min)*60+int(sec)
        button.configure(command=lambda count=time:countdown(count))

for widget in (hoursE,minuteT,secondE):
    widget.bind("<FocusOut>", updateButton)