嗨,我无法确定下一步该做什么。 我希望alarm_label在Tkinter小部件打开后更新时间。 任何想法都受到赞赏。我在网上查看过线程,但他们似乎对我的做法完全不同,我确信这对我来说是一个简单的方法让这个时钟工作。
from Tkinter import *
import time
#Window
alarm_window = Tk()
#Title
alarm_window.title('Alarm')
def off_press():
alarm_window.destroy()
#Alarm Class
class Clock(object):
def __init__ (self, time, sleep):
self.time = time
self.sleep = sleep
print "The time and date is %s" % (self.time) #temporary to see if it's working
#Alarm
alarm_label = Label(alarm_window, text = self.time)
alarm_label.grid (row = 0, column = 1)
def refresh_time():
for each in range(2): #only temporary until I find a way to make the label update
alarm = Clock(time.ctime(), time.sleep(1))
#Off Button
off = Button(alarm_window, text = "Off", command = off_press)
off.grid (row = 1, column = 2)
#Snooze
snooze = Button(alarm_window, text = "Snooze")
snooze.grid (row= 1, column = 0)
#Run Program
refresh_time()
alarm_window.mainloop()
答案 0 :(得分:2)
您可以使用Tk().after(1000, refresh_time)
每秒更新一次
而不是创建新标签来显示时间使用label.configure(text=)
来更改标签文本。
我做了一些修改以显示示例时钟:
from Tkinter import *
import time
#Window
alarm_window = Tk()
#Title
alarm_window.title('Alarm')
def off_press():
alarm_window.destroy()
#Alarm Class
class Clock(object):
def __init__ (self, time):
self.time = time
print "The time and date is %s" % (self.time) #temporary to see if it's working
#Alarm
# Create instance variable to use it in "refresh_time"
self.alarm_label = Label(alarm_window, text = self.time)
self.alarm_label.grid (row = 0, column = 1)
def refresh_time():
#for each in range(2): #only temporary until I find a way to make the label update
#Change label text with "configure(text=)" method
clock.alarm_label.configure(text=time.ctime())
#Use recursivity to make call after 1 second
alarm_window.after(1000, refresh_time)
#Off Button
off = Button(alarm_window, text = "Off", command = off_press)
off.grid (row = 1, column = 2)
#Snooze
snooze = Button(alarm_window, text = "Snooze")
snooze.grid (row= 1, column = 0)
#Run Program
#refresh_time()
#Create "clock" label
clock = Clock(time.ctime())
#Run "refresh_time" after 1 second
alarm_window.after(1000, refresh_time)
alarm_window.mainloop()