简体   繁体   中英

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. 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.
Instead of creating new label to show time use label.configure(text=) to change label 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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM