Search code examples
pythoncanvastkintercountdown

Tkinter Canvas is not showing


So I was trying to make a countdown in python using tkinter, but somehow the canvas windows is not showing... I don't really know why, can anyone help me?

import tkinter
import random
import time
canvas=tkinter.Canvas(height=350,width=400,)
canvas.pack()

t=10

def c():
    global t
    while t>=0:
        if t == 0:
            canvas.create_text(100,10, text="YOU LOST!")


        else:
            time.sleep(1)        
            t-=1
            canvas.create_text(50,50, text=t, font="Aria 25", fill="red")
            print(t)            

c()

Solution

  • The main problem is you never call the mainloop() method, which is necessary in all tkinter application because it's what makes the GUI function.

    In addition, you should never call time.sleep() in a tkinter application because it interferes with mainloop() and will cause your program to "hang".

    To overcome these restrictions, you can use the universal after() method that all widgets have. Here's some documentation about it.

    Note how the c() function no longer contains a while loop. Instead it calls after() itself and passes itself to it as the function to be called after the delay — this keeps things going until the count reaches zero.

    To make things more efficient, I also modified your code so it only creates one Canvas text object and then updates it afterwards. This prevents creation of a bunch of Canvas text objects from piling-up on top of one another that are no longer needed.

    import tkinter
    
    canvas = tkinter.Canvas(height=350,width=400,)
    canvas.pack()
    
    DELAY = 1000  # milliseconds.
    t = 10
    text_obj_id = None
    
    def c():
        global t
        global text_obj_id
    
        if t >= 0:
            if t == 0:
                canvas.create_text(100, 10, text="YOU LOST!")
            else:
                t -= 1
    
                if text_obj_id is None:  # First time?
                    text_obj_id = canvas.create_text(50, 50, text=t, font="Aria 25",
                                                     fill="red")
                else:  # Update existing Canvas text object.
                    canvas.itemconfigure(text_obj_id, text=t)
    
                print(t)
    
                canvas.after(DELAY, c)  # call again in 1000 ms.
    
    c()  # Starts repeated calling of function.
    canvas.mainloop()