Arc*_*ran 1 python time tkinter
我已经为 python 计时器编写了一些代码,但是当我运行它时,我得到一个错误,但问题是我不知道该怎么做,所以我在互联网上搜索了所有帮助后来到这里寻求帮助,但我不能'找不到与我的问题相匹配的任何内容。
这是错误:
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
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
# 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()
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我吗?
提前致谢!
小智 5
您必须声明sec
为start
. 以下是修复错误的方法:
# 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()
Run Code Online (Sandbox Code Playgroud)
但是,这仍然存在问题,因为它会因while
循环而冻结屏幕。使用 tkinter 构建计时器的更好方法是这样的:
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()
Run Code Online (Sandbox Code Playgroud)
另外,对未来的一些建议:永远不要在 GUI 中使用time.sleep
或while
循环。而是利用 GUI 的主循环。它将避免许多令人头疼的事情冻结或崩溃。希望这可以帮助!