Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- from datetime import datetime
- import time as pytime # TIP: datetime also contains time so this makes it easier if using both.
- from threading import Thread
- class TKGUI:
- def __init__(self):
- self.root= Tk() ##initilise the main window
- self.quit = False ##defaults the quit flag
- self.time = "00:00:00"
- def update_time(self): #this just sets the self.time variable to the current time
- self.time = datetime.now().strftime("%H:%M:%S")
- def time_thread(self): #This will run as a thread
- while not self.quit:
- self.update_time()
- pytime.sleep(0.5) #best to add some form of delay to a thread or it uses too much CPU power to run simple things
- def update_time_lable(self): #updates the lable
- self.time_L.configure(text=self.time)
- def run(self): ##main part of the application
- self.root.configure(bg="white") #sets the background to white rather than default gray.
- self.root.protocol("WM_DELETE_WINDOW", self.quitting) ##changes the X (close) Button to run a function instead.
- try:
- self.root.iconbitmap("fav.ico") ##sets the application Icon
- except:
- pass
- self.root.title("MyApp")
- self.root.geometry("800x600")
- #############################################################
- #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
- #----------------------Code Goes Here ----------------------#
- #///////////////////////////////////////////////////////////#
- #############################################################
- self.time_L = Label(self.root, text=self.time, bg="white", font=("Courier", 44)) # The label to hold the time
- self.time_L.pack(side=TOP)
- #############################################################
- t=Thread(target=self.time_thread)
- t.start()
- while not self.quit: ##flag to quit the application
- self.root.update_idletasks() #updates the root. same as root.mainloop() but safer and interruptable
- self.root.update() #same as above. This lest you stop the loop or add things to the loop.
- #add extra functions here if you need them to run with the loop#
- if self.time != self.time_L.cget("text"): #adding this for a condition
- self.update_time_lable() #run a function in the mainloop
- def quitting(self): ##to set the quit flag
- self.quit = True
- if __name__ == "__main__":
- app = TKGUI() ##creates instance of GUI class
- try:
- app.run()# starts the application
- except KeyboardInterrupt:
- app.quitting() ##safely quits the application when crtl+C is pressed
- except:
- raise #you can change this to be your own error handler if needed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement