【发布时间】:2020-07-30 04:56:11
【问题描述】:
我正在尝试编写 python 代码,该代码将使用 tkinter 在输入框中显示秒表。
我的想法是使用递归函数,每秒使用 time.sleep(1) 将 1 添加到盒子中。
我被难住了——当我按下任一按钮时都没有任何反应,而且我没有收到错误代码,所以我不知道为什么它不起作用。
我只有在按下停止后才会在框中看到任何东西,而且总是“00:00:00”。
from tkinter import *
import time
root = Tk()
root.title("Stopwatch")
#box to display stopwatch
box = Entry(root, width = 20, borderwidth = 5)
box.grid(row = 0, column = 0)
#displays stopwatch in the box
def show_timer():
global hrs, mins, secs, timer
timer = str(hrs).zfill(2) + ":" + str(mins).zfill(2) + ":" + str(secs).zfill(2)
box.delete(0, END)
box.insert(0, timer)
#check = 1 allows the stopwatch to run
def set_check(i):
global check
check = i
return check
#actual function for stopwatch
def stopwatch():
global check, hrs, mins, secs
if check == 1:
time.sleep(1)
if int(secs) < 59:
secs += 1
return secs
elif mins < 59:
mins += 1
secs = 0
return mins, secs
else:
hrs += 1
mins = 0
secs = 0
return hrs, mins, secs
show_timer()
stopwatch()
else:
show_timer()
def start():
global hrs, mins, secs
hrs, mins, secs = 0, 0, 0
return hrs, mins, secs
show_timer()
set_check(1)
stopwatch()
def stop():
set_check(0)
stopwatch()
start_button = Button(root, text = "Start", command = start)
stop_button = Button(root, text = "Stop", command = stop)
start_button.grid(row = 1, column = 0)
stop_button.grid(row = 2, column = 0)
root.mainloop()
【问题讨论】:
-
return离开当前的函数调用,所以你的def start(...什么都不做。阅读Tutorial - 4.6. Defining Functions