Today we’re going learn how to create a Simple Digital Clock using Python in a few lines of code. For building this Clock up we will require the tkinter and time module.
Requirements for building a Digital Clock in Python
First, we need to install the Tkinter module. If you don’t have this module already installed in your system then you can install the same using the pip package manager:
C:\Users\Admin>pip install tkinter
Once your tkinter module is successfully installed on your system you’re good to go.
Coding the Digital Clock in Python
We’ll be using the tkinter module and the time module to build our clock today.
1. Tkinter Module
Tkinter is the standard GUI library for Python. Tkinter gets its name from Tk interface. When python is combined with Tkinter it provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Tkinter is a Python binding to the Tk GUI toolkit.
2. Time Module
Time module provides a variety of ways of getting time, In this article, we are going to use strftime() to parse the current time into the Hour: Minutes: Seconds format.
3. Implementing the digital clock
In this code, we will use geometry() to specify the dimension of the displayed window and we will use mainloop() to prevent the displayable window from exiting quickly.
#import all the required libraries first import sys from tkinter import * #import time library to obtain current time import time #create a function timing and variable current_time def timing(): #display current hour,minute,seconds current_time = time.strftime("%H : %M : %S") #configure the clock clock.config(text=current_time) #clock will change after every 200 microseconds clock.after(200,timing) #Create a variable that will store our tkinter window root=Tk() #define size of the window root.geometry("600x300") #create a variable clock and store label #First label will show time, second label will show hour:minute:second, third label will show the top digital clock clock=Label(root,font=("times",60,"bold"),bg="blue") clock.grid(row=2,column=2,pady=25,padx=100) timing() #create a variable for digital clock digital=Label(root,text="AskPython's Digital Clock",font="times 24 bold") digital.grid(row=0,column=2) nota=Label(root,text="hours minutes seconds",font="times 15 bold") nota.grid(row=3,column=2) root.mainloop()
This is how you can create a simple Digital Clock in Python programming! What are you waiting for? Create your own by trying the code yourself!