Home > Enterprise >  Make tk.Mainloop Reachable
Make tk.Mainloop Reachable

Time:01-19

I am trying to make a clock in python using tkinter. But I am getting an issue where tk.mainloop is not reachable

tk = Tk()

tk.geometry("800x600")

tk.title("Clock")



Here is the code

from tkinter import *
import time


tk = Tk()


def Clock():
    
    while True:
        from datetime import datetime

        now = datetime.now()

        clock = Label(tk, text=(now.month,now.day,now.year,now.hour,now.minute))

        clock.pack()

        time.sleep(60)

        tk.after(1)

        tk.after(1, Clock)

Clock()

tk.mainloop()

CodePudding user response:

Here is small code for newbie.

Code:

from tkinter import *
import datetime as dt


tk = Tk()
tk.title('Clock')

def Clock():    
    day = f"{dt.datetime.now():%H:%M:%S.%p}"
    now = f"{dt.datetime.now():%a, %b %d %Y}"
    
    clock.config(text= f'{now} { day}')

    tk.after(1000, Clock)

clock = Label(tk, fg="white", bg="black", font=("helvetica", 40))
clock.pack()

Clock()

tk.mainloop()

Screenshot:

enter image description here

CodePudding user response:

Tkinter depends on a loop to work, so you can't use loops inside it, it will cause code crash, some internal functions like 'after' can help...

from datetime import datetime
from tkinter import *

root = Tk()

root.geometry("800x600")
root.title("Clock")

clock = Label(root, text='')
clock.pack()


def update_clock():
    now = datetime.now()
    new_text = str((now.month, now.day, now.year, now.hour, now.minute, now.second))
    print(new_text)
    clock.config(text=new_text)
    root.after(1000, update_clock)


if __name__ == '__main__':
    update_clock()
    root.mainloop()
  • Related