Tkinter GUI displaying real time clock with Weekday and date in different formats
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("405x170")
from time import strftime
def my_time():
time_string = strftime('%H:%M:%S %p') # time format
l1.config(text=time_string)
l1.after(1000,my_time) # time delay of 1000 milliseconds
my_font=('times',52,'bold') # display size and style
l1=tk.Label(my_w,font=my_font,bg='yellow')
l1.grid(row=1,column=1,padx=5,pady=25)
my_time()
my_w.mainloop()
We are calling the same function my_time() at an interval of 1 sec ( 1000 milliseconds ) by using l1.after(1000,my_time)
Managing Clock display format
Add date and Month name in next line. Here we changed the background colour of the Label to bg='#53fcf7'
time_string = strftime('%H:%M:%S %p \n %d %B')
Display Local date ( %x ) along with clock.
time_string = strftime('%H:%M:%S %p \n %x')
With Full weekday
time_string = strftime('%H:%M:%S %p \n %A \n %x')
Here is a list of formats can be used with strftime()
Adding time to Entry box on Button click
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x140")
from time import strftime
def my_time(): # On button click
time_string = strftime('%H:%M:%S %p')e1_str.set(time_string) # adding time to Entry
l1 = tk.Label(my_w, text='Add Time', width=10 )
l1.grid(row=1,column=1,padx=10,pady=30)
e1_str=tk.StringVar()
e1 = tk.Entry(my_w, textvariable=e1_str,width=15) # Entry box
e1.grid(row=1,column=2)
b1 = tk.Button(my_w, text='Update', width=8,bg='yellow',
command=lambda: my_time())
b1.grid(row=1,column=3)
my_w.mainloop()
One more set of input and buttons can be added to record the start time and end time of any process.
List of formats used for generating date and time
Format
Meaning
%a
Locale’s abbreviated weekday name.
%A
Locale’s full weekday name.
%b
Locale’s abbreviated month name.
%B
Locale’s full month name.
%c
Locale’s appropriate date and time representation.
%d
Day of the month as a decimal number [01,31].
%H
Hour (24-hour clock) as a decimal number [00,23].
%I
Hour (12-hour clock) as a decimal number [01,12].
%j
Day of the year as a decimal number [001,366].
%m
Month as a decimal number[01,12].
%M
Minute as a decimal number[00,59].
%p
Locale’s equivalent of either AM or PM.
%S
Second as a decimal number[00,61].
%U
Week number of the year(Sunday as the first day of the week) as a decimal number[00,53]. All days in a new year preceding the first
Sunday are considered to be in week 0.
%w
Weekday as a decimal number [0(Sunday),6].
%W
Week number of the year (Monday as the first day of
the week) as a decimal number[00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x
Locale’s appropriate date representation.
%X
Locale’s appropriate time representation.
%y
Year without century as a decimal number [00,99].
%Y
Year with century as a decimal number.
%Z
Time zone name (no characters if no time zone exists).