Home > database >  Not proceeding with code after while loop
Not proceeding with code after while loop

Time:04-26

I'm trying to make a simple digital clock using Tkinter. However, after I use "while True" to update the variable and the label, it doesn't create a window, even though that part is not indented. Here's my code:

from datetime import datetime
from tkinter import *

root = Tk()
root.geometry('400x200')

while True
    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")

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


root.update()
``

CodePudding user response:

I haven't written any python before, however I imagine that while true is always true, therefore you have an infinite loop where your variable now is being constantly updated with the new time, with no chance to break free from the loop

CodePudding user response:

while True:
...

Program is stucked in this part it will keep on executing it.

In order to solve the issue move while True logic inside a thread(use Thread from threading module).

Here's another simple approach we are using clock.after(400, update) which will call after 400 milliseconds and update the label we are using mainloop to ensure that main will not exit till our window is not closed.

from datetime import datetime
from tkinter import *

root = Tk()
root.geometry('400x200')

clock = Label(root)
clock.pack()

def update():
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print(current_time)
    clock.config(text=current_time)
    clock.after(400, update)



root.update()

update()

mainloop()

CodePudding user response:

Check here to see how to create a clock with tkinter. https://www.geeksforgeeks.org/python-create-a-digital-clock-using-tkinter/

Your code will never exit the loop because while will be always looping at a very high speed because the condition is always (True).

  • Related