Digital Clock
Tkinter, Frame, Canvas
Script for displaying a digital clock as
shown in Figure 1 is shown in listing 1
Figure
1
Listing 1 Script for displaying a digital clock shown in Figure 1.
import tkinter as tk
from datetime
import datetime
root = tk.Tk()
def f_close(event):
root.destroy()
frame = tk.Frame(root)
button = tk.Button(frame,
text = 'Close')
button.grid(row = 0, column = 10, padx = 5, sticky = 'e')
button.bind('<Button-1>', f_close)
canvas = tk.Canvas(frame,
bg = '#ffffff', width =
800, height = 400)
canvas.grid(row = 1, columnspan
= 11, rowspan = 1)
frame.pack()
canvas.create_text(400, 200, text = ' ', font = ('Gothic', 100), tags = 'mytext')
def check_time():
now
= datetime.now()
s = '{0:0>2d}:{1:0>2d}:{2:0>2d}'.format(now.hour,
now.minute, now.second)
canvas.itemconfig('mytext', text = s)
root.after(100, check_time)
check_time()
root.mainloop()
Run the script in listing 1, then the digital clock shown in Figure 1 is displayed.
The time displayed is
updated by the following code.
root.after(100, check_time)
This code set the function check_time to be called after 100
msec.
Click on the button Close
at the upper right, then the function f_close is
called. This binding of the event click and the function f_close
is set by the following code.
button.bind('<Button-1>', f_close)
The function f_close is set as follows:
def f_close(event):
root.destroy()
Running the program ends by executing code root.destroy().