Tuesday, July 19, 2016

Creating a Digital clock in Python 3 using TkInter GUI library

Hello there,

Have you been thinking of creating your own digital clock on your windows PC?

Today, I will share with you how to go about it using Python 3 TkInter GUI library

Open your command prompt (cmd), enter python interactive prompt and follow me along




STEP 1:

We first of all import TkInter GUI library and strftime() function from time module.

Type in the following:

import tkinter
from time import strftime



STEP 2:

Next step, we create the clock frame object and write an arbitrary text on it. Then we test that the frame text properties can be changed. See the code below:

clock_frame = tkinter.Label()
clock_frame['text'] = '19:12:09'
clock_frame.pack()

# test that the frame text properties can be changed
clock_frame['text'] = '19:38:00'
clock_frame['font'] = 'Helvatica 120 bold'
clock_frame['fg'] = 'red'




STEP 3:

In this step, we will replace the arbitrary text above with the current time of the PC using the strftime() function. But first we will store the time in a variable named "current_time" and then use the variable in a function later.

current_time = strftime("%H:%M:%S")
print (current_time)


STEP 4:

Lets create two functions tic() and tac() to hold the current time and refresh the time after every 1000 milliseconds  respectively. Now if we call the tac() function, our digital clock should be working as usually with any digital clock.

# this function holds the PC current time on our frame
def tic():
 clock_frame['text'] = strftime("%H:%M:%S")

# this function refreshes the tic() function after 1000miliseconds
def tac():
 tic()
 clock_frame.after(1000, tac)

tac()




The completed code all together is as seen below:-


# Digital Clock with Python TkInter library
# digitalclk.py
# By: www.UmarYusuf.com
# To be executed on Python3 via command prompt


# we import Tk GUI library and strftime function from time module
import tkinter
from time import strftime


clock_frame = tkinter.Label()
clock_frame['text'] = '19:12:09'
clock_frame.pack()

# test that the frame text properties can be changed
clock_frame['text'] = '19:38:00'
clock_frame['font'] = 'Helvatica 120 bold'
clock_frame['fg'] = 'red'

# using the PC current time instead of text
current_time = strftime("%H:%M:%S")
print (current_time)


# this function holds the PC current time on our frame
def tic():
 clock_frame['text'] = strftime("%H:%M:%S")

# this function refreshes the tic() function after 1000miliseconds
def tac():
 tic()
 clock_frame.after(1000, tac)

tac()



That is it.
You now know how code a digital clock on your PC.

No comments:

Post a Comment