Python Digital Clock Program using tkinter GUI

By | March 25, 2020

Topic: Python Digital Clock Program using tkinter GUI

Hardly 10 Lines of code using a label control and after() method to call a function after given miliseconds. This program imports time module We use time module and tkinter.

Program Logic / Widgets used in Digital clock Program

  1. Label widget: create a label widget named clock
  2. Set fore ground(font) color and background color
  3. Use after() method defined for the widgets
  4. after() method takes two parameters here: 1. time in milli seconds after which to call a function 2. name of the function to call after specified number of milli seconds.
  5. Therefore the code will get time from the system and update it on a label widget after 1 second.

"<yoastmark

from tkinter import *

import time

main_window = Tk()
clock = Label(main_window, font=('arial', 100, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)
def tick():
    s = time.strftime('%H:%M:%S')
    if s != clock["text"]:
        clock["text"] = s
    clock.after(200, tick)


tick()
main_window.mainloop()

How Digital Clock Program Works

Python Digital Clock Program using tkinter GUI

from tkinter import *

import time

main_window = Tk()
[create a label named clock, set font options etc.]
clock = Label(main_window, font=('arial', 100, 'bold'), bg='green')
[Place clock label into main window]
clock.pack(fill=BOTH, expand=1)
[define a user defined function tick()
 we will call this function again and again after
 200 milli seconds]
def tick():
    [ get time in a string s]
    s = time.strftime('%H:%M:%S')
    [if need to update time (after 1 second)
       then update otherwise pass]
    if s != clock["text"]:
        clock["text"] = s
    [call tick function after 200 milliseconds]
    clock.after(200, tick)

[ start tick function]
tick()
[ start mainloop to start GUI of the program
main_window.mainloop()

You will also like to read:

Loading

One thought on “Python Digital Clock Program using tkinter GUI

  1. Pingback: Python GUI Area of Triangle | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *