tkinter 中的基本计时器 [英] Basic timer in tkinter
问题描述
我已经为 python 计时器编写了一些代码,但是当我运行它时,我得到一个错误,但问题是我不知道该怎么做,所以我在互联网上搜索了所有帮助后来到这里寻求帮助,但是我找不到与我的问题相符的内容.
I have written some code for a python timer but when ever I run it I get an error but the thing is I don't know what to do so I came here for help after I searched all over the internet for help but I couldn't find anything that matched my problem.
这里是错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Users\Public\Documents\Programming\Timer.py", line 27, in start
sec = sec + 1
UnboundLocalError: local variable 'sec' referenced before assignment
这是我的代码:
# Import Modules
from tkinter import *
import time
# Window Setup
root = Tk()
root.title('Timer')
root.state('zoomed')
# Timer Variables
global sec
time_sec = StringVar()
sec = 0
# Timer Start
def start():
while 1:
time.sleep(1)
sec = sec + 1
time_sec.set(sec)
start()
# Timer Setup
Label(root,
textvariable=time_sec,
fg='green').pack()
Button(root,
fg='blue',
text='Start',
command=start).pack()
# Program Loop
root.mainloop()
有人可以帮我吗?
提前致谢!
推荐答案
您必须将 sec
声明为 start
的全局内部.以下是修复错误的方法:
You have to declare sec
to be a global inside of start
. Here is how to fix the error:
# Import Modules
from tkinter import *
import time
# Window Setup
root = Tk()
root.title('Timer')
root.state('zoomed')
# Timer Variables
global sec
time_sec = StringVar()
sec = 0
# Timer Start
def start():
while 1:
time.sleep(1)
### You have to declare sec as a global ###
global sec
sec = sec + 1
time_sec.set(sec)
start()
# Timer Setup
Label(root,
textvariable=time_sec,
fg='green').pack()
Button(root,
fg='blue',
text='Start',
command=start).pack()
# Program Loop
root.mainloop()
然而,这仍然有问题,因为它会由于 while
循环而冻结屏幕.使用 tkinter 构建计时器的更好方法是这样的:
However, this still has problems because it freezes the screen due to the while
loop. A better way to build a timer with tkinter is like this:
from tkinter import *
root = Tk()
root.title('Timer')
root.state('zoomed')
sec = 0
def tick():
global sec
sec += 1
time['text'] = sec
# Take advantage of the after method of the Label
time.after(1000, tick)
time = Label(root, fg='green')
time.pack()
Button(root, fg='blue', text='Start', command=tick).pack()
root.mainloop()
另外,对未来的一些建议:永远不要在 GUI 中使用 time.sleep
或 while
循环.而是利用 GUI 的主循环.它将避免许多令人头疼的事情冻结或崩溃.希望这会有所帮助!
Also, some advice for the future: never use time.sleep
or a while
loop like that in a GUI. Take advantage of the GUI's mainloop instead. It will save many headaches of stuff freezing or crashing. Hope this helps!
这篇关于tkinter 中的基本计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!