[英]Python Clock (Simple Mistake?)
Hi I can't work out what to do next. 嗨,我不知道下一步该怎么做。 I want the alarm_label to update the time once the Tkinter widget is open.
Tkinter小部件打开后,我希望alarm_label更新时间。 Any ideas at all are appreciated.
任何想法都值得赞赏。 I've looked at threads online but they seem to be doing it a completely different way to me, I'm sure theres a simple way for me to get this clock working.
我看过在线线程,但是他们似乎对我来说是一种完全不同的方式,我敢肯定有一种简单的方法可以使我的时钟正常工作。
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()
You can use Tk().after(1000, refresh_time)
to update time each second. 您可以使用
Tk().after(1000, refresh_time)
每秒更新时间。
Instead of creating new label to show time use label.configure(text=)
to change label text. 不用创建新标签来显示时间,而是使用
label.configure(text=)
更改标签文本。
I made little modifications to show a sample clock: 我做了一些修改以显示示例时钟:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.