0

So basically, I'm trying to make a digital clock in python, to show up on a little window when I run the program. I had two ideas on how to make these, but the code below is the same. My problem is: if I use the time.sleep command, when I run the program, the window doesn't even pop up, but if I use root.after(1000, clock(root, w), the window appears but it creates 1000 of the labels, giving the "recursion depth exceeded" error. Any help?

import time as t
import tkinter as tk

from datetime import datetime

def main():
    root = tk.Tk()
    root.title("Digital Clock")
    w = tk.Label(font = (100))
    w.pack()
    clock(root, w)
    root.mainloop()

def clock(root, w):
    t.sleep(1)
    timelabeled = " "
    now = datetime.now()
    timelabeled = ("%s/%s/%s   %s:%s:%s" % (now.day, now.month, now.year, now.hour, now.minute, now.second))

    w.config(text = timelabeled, )
    root.after(clock(root, w))   

if __name__ == "__main__":
    main()

My result is supposed to be a little window with a label representing the time, which gets updated every second, but that's not what I'm getting. Either I get nothing, or 1000 labels that don't update.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Borlikk
  • 1
  • 1
  • 1
    The 1000 labels issue is because you're running `clock(root, w)` inside the `clock` function - infinite recursion. –  Apr 12 '19 at 04:11

2 Answers2

0

You could just use root.after to repeat the function every 1 second. No sleep is required.

import tkinter as tk

from datetime import datetime

root = tk.Tk()
root.title("Digital Clock")

def clock():
    now = datetime.now()
    timelabeled = ("%s/%s/%s   %s:%s:%s" % (now.day, now.month, now.year, now.hour, now.minute, now.second))
    w.config(text = timelabeled, )
    root.after(1000,clock)

w = tk.Label(font = (100))
w.pack()
clock()
root.mainloop()
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • so i guess my problem was with the "main". Once i removed the "def main()" just like in your code, everything worked flawlessly. Can you explain why that happened though? I have no idea... Thanks in advance! – Borlikk Apr 12 '19 at 11:08
  • it is a scope problem and not necessary related to tkinter. Basically you can't just pass local variables around different functions - you need to declare global, or use OOP instead. – Henry Yik Apr 12 '19 at 12:37
0

Its just a simple clock using Tkinter module for a software look:

from tkinter import *
from time import strftime

root=Tk()
root.title("clock")

def time():
    string=strftime("%H: %M: %S: %p")
    label.configure(text=string)
    label.after(1000, time) 

label=Label(root, font=("Arial Black", 40),bg="black", fg="white")
label.pack(anchor="center")


time()
root.mainloop()
harshath
  • 1
  • 2