我刚刚写的程序是我用来了解Tkinter是如何工作的。
我的问题是如何将变量“timelabel”显示为标签。在
我准备好了一个名为timerefresher的标签,但它没有出现。在
我知道DigitalClock类的编写效率不高。我是新手;)。在
def Clockupdate(time):
timelabel = time
timerefresher = Label(root, textvariable=timelabel)
timerefresher.pack()
#print(timelabel) To test if variable made it this far.
class DigitalClock:
def secondrefesher(self):
newtime = ""
while 1 == 1:
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a+":"+b+':'+c)
if curtime != newtime:
newtime = curtime
#print("made it here")
Clockupdate(newtime)
else:
time.sleep(0.20)
DC = DigitalClock()
root = Tk()
mainlabel = Label(root, text="Hey this is working!")
Pressme = Button(root, text="Press me!", command=Presstoshowtextandpic,
bg='red', fg='white')
Clock = Button(root, text="Clock?", command=DC.secondrefesher, bg='blue',
fg='white')
Photo = PhotoImage(file="test.png")
ShowPhoto = Label(root, image=Photo)
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
好的,这里是我将如何使用你的代码来完成你正在尝试做的事情。在
首先,让我们确保我们有正确的进口。在
我创建了这个
^{pr2}$doNothing()
函数作为我当前没有测试的任何命令的占位符。在现在,您使用
Clockupdate(time):
函数的方式将导致每次单击时钟按钮时都添加标签。所以这可能不是你想要的,因为它只是不断地添加新的标签,而不是替换现有的标签。看看这个函数。我在这里所做的就是.config()
文本作为函数的时间参数。请注意,您不需要重新定义时间标签或任何类似的东西,只需使用时间作为变量。在我不知道您是否想使用一个类是出于特定的原因,但我认为您应该在这里使用一个函数。也要尽量保持你的报价一致。我知道它们是可互换的,但保持它们的一致性是很好的做法。在
注意我总是把命令放在按钮配置的末尾。它有助于管理代码,这样您就可以在滚动代码时检查每行的末尾。我还将Pressme的命令改为doNothing,这样我就可以测试代码了。您没有为Presstoshowtextandpic提供代码,因此无法在没有该部分的情况下测试代码。记得在这里提问时使用MCVE。在
在这里,我只创建了一次时间标签,然后您可以调用update函数将文本更改为当前时间。在
下面是我认为完成的代码应该是什么样子。在
编辑:
如果您试图创建一个始终处于活动状态且不需要您单击按钮的时钟,则可以使用
.after()
。在看看这个例子。在
您应该编写一个MCVE,这样就可以测试您的代码,特别是缺少的东西(例如
Presstoshowtextandpic()
)。在在阅读其余代码时,我认为您需要阅读关于variable classes的内容,并按如下方式修改Clockupdate():
另外,你应该写^{} 而不是
Clockupdate()
相关问题 更多 >
编程相关推荐