Skip to content

Commit 026b56e

Browse files
Digital Clock: consolidate update loop and refresh every second
1 parent 0173fc9 commit 026b56e

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

Digital Clock/main.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,44 @@
77
window.configure(bg="green")
88
window.resizable(False, False)
99

10+
use_24h = True
11+
1012
clock_label = Label(
1113
window, bg="black", fg="green", font=("Arial", 30, "bold"), relief="flat"
1214
)
1315
clock_label.place(x=50, y=50)
1416

15-
# NEW date label
17+
1618
date_label = Label(
1719
window, bg="black", fg="white", font=("Arial", 14)
1820
)
1921
date_label.pack(pady=(0, 10), anchor="center")
2022

2123

2224

25+
def toggle_format(_evt=None):
26+
global use_24h
27+
use_24h = not use_24h
28+
fmt_btn.config(text="Switch to 24-hour" if not use_24h else "Switch to 12-hour")
29+
30+
fmt_btn = Button(window, text="Switch to 12-hour", command=toggle_format)
31+
fmt_btn.pack(pady=(0, 8))
32+
window.bind("<f>", toggle_format) # press 'f' to toggle
33+
34+
35+
2336
def update_label():
24-
current_time = strftime("%H: %M: %S\n %d-%m-%Y ")
25-
clock_label.configure(text=current_time)
26-
clock_label.after(80, update_label)
27-
clock_label.pack(anchor="center")
37+
38+
if use_24h:
39+
time_text = strftime("%H:%M:%S")
40+
else:
41+
# strip leading zero in 12h mode for a cleaner look
42+
time_text = strftime("%I:%M:%S %p").lstrip("0")
43+
clock_label.configure(text=time_text)
44+
date_label.configure(text=strftime("%A, %b %d, %Y"))
45+
window.after(1000, update_label)
2846

2947
update_label()
30-
window.mainloop() def update_label():
31-
clock_label.configure(text=strftime("%H:%M:%S"))
32-
date_label.configure(text=strftime("%A, %b %d, %Y"))
33-
clock_label.after(1000, update_label)
48+
window.mainloop()
49+
3450

0 commit comments

Comments
 (0)