我已经为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
这是我的代码:
# 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()
有人可以帮助我吗?
提前致谢!
答案 0 :(得分:4)
您必须将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()
然而,这仍然存在问题,因为它会因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()
此外,对未来的一些建议:永远不要在GUI中使用time.sleep
或while
循环。而是利用GUI的主循环。这将拯救许多令人头疼的东西冻结或崩溃。希望这有帮助!
答案 1 :(得分:0)
您必须在start.ie中启动global sec
:
......
# Timer Start
def start():
global sec
.....
你可以把它放在class
中。这样你就不用担心变量的范围..
from tkinter import *
import time
class App():
def __init__(self):
self.window = Tk()
self.root = Frame(self.window, height=200,width=200)
self.root.pack()
self.root.pack_propagate(0)
self.window.title('Timer')
self.label = Label(text="")
self.label.pack()
self.sec = 0
self.timerupdate()
self.root.mainloop()
def timerupdate(self):
self.sec = self.sec + 1
self.label.configure(text=self.sec)
self.root.after(1000, self.timerupdate)
app=App()
app.mainloop()