所以,我正在尝试使用start在tkinter程序中创建一个时钟。根据文档,第一个应该调用一个函数,然后你应该将after函数放在被调用的函数中,使它一遍又一遍地运行。但是,当我这样做时,第一个之后将调用我的函数就好了,然后在我的函数之后的调用将告诉我函数没有定义。我不明白为什么会发生这种情况或如何解决它。
首先调用after是在底部,它调用updateTime()函数。它在该函数中应该在1秒延迟后调用自身,但是会给出错误。
另外,我是python和tkinter的新手,所以如果这是错误的方法,请告诉我。 after函数似乎是最好的方法。
from Tkinter import *
import time
#from relayControl import switchOnOff
#Pin numbers:
#Light: 2
#Fan: 3
class Main:
def exit():
quit()
def lightSwitch():
print("Light on")
#switchOnOff(2)
def fanSwitch():
print("Fan on")
#switchOnOff(3)
def updateTime(timeLabel, root):
timeLabel.config(text=time.strftime("%H:%M:%s", time.localtime()))
root.after(100, updateTime(timeLabel, root))
root = Tk()
root.configure(background="black")
root.columnconfigure(1, weight=1)
root.columnconfigure(2, weight=1)
root.columnconfigure(3, weight=1)
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
root.rowconfigure(3, weight=1)
# ***Time(center)***
timeLabel = Label(root, text=time.strftime("%H:%M:%s", time.localtime()), bg="black", fg="red")
timeLabel.grid(row=2, column=2)
# ***Alarm(top left)***
alarmLabel = Label(root, text="Alarm Time", bg="black", fg="red")
alarmLabel.grid(row=1, column=1)
# ***Exit(bottom right)
exitButton = Button(root, text="Exit", bg="red", highlightbackground="red", command=exit)
exitButton.grid(row=3, column=3)
# ***Frequently used switches(top right)***
buttonFrame = Frame(root, bg="black")
buttonFrame.grid(row=1, column=3)
lightSwitch = Button(buttonFrame, text="Light", bg="red", highlightbackground="red", command=lightSwitch)
lightSwitch.pack()
fanSwitch = Button(buttonFrame, text="Fan", bg="red", highlightbackground="red", command=fanSwitch)
fanSwitch.pack()
root.after(100, updateTime(timeLabel, root))
root.mainloop()
错误:
Traceback (most recent call last):
File "/home/leemorgan/projects/python/automatedHome/main.py", line 9, in <module>
class Main:
File "/home/leemorgan/projects/python/automatedHome/main.py", line 60, in Main
root.after(100, updateTime(timeLabel, root))
File "/home/leemorgan/projects/python/automatedHome/main.py", line 24, in updateTime
root.after(100, updateTime(timeLabel, root))
NameError: global name 'updateTime' is not defined
答案 0 :(得分:0)
我认为您需要lambda
命令,请尝试:
root.after (100, lambda timeLabel = timeLabel, root = root: Main.updateTime (timeLabel, root))
编辑: 使用Brian Oakley的评论(一种更好的方法):
root.after (100, Main.updateTime, timeLabel, root)