Python Overwriting text in Tkinter
Question: I'm having some trouble updating the countdown timer text printed on a canvas.
My current code leaves the area where the text should be blank.

I've tried placing it in various places, but they all lead to no effect or the
same effect I described above. Removing the `canvas.delete` function just
leads to the new time being written on top of the old one.

Here is my current code:

    
    
    def cdtimerr():
        global cdtimer
        cdtimer -= 1
        cdtext = canvas.create_text(510, 6, text=cdtimer, font="Ubuntu 29 bold", anchor = NW) 
        if cdtimer == 0 :
            canvas.delete(ALL)
            scorescreen()
        else:
            canvas.after(1000, cdtimerr)
            canvas.after(1000, canvas.delete(cdtext))
    

Also, how would I go about terminating the timer prematurely if I pressed an
exit button on the canvas which loads another screen? Currently, if I load
another screen the timer still continues.


Answer: To cancel timer. Save return value of `after`, call `after_cancel` with saved
value.

    
    
    from Tkinter import *
    
    remain = 11
    _timer = None
    def cdtimerr():
        global remain, _timer
        remain -= 1
        cdtext = canvas.create_text(510, 6, text=remain, font="Ubuntu 29 bold", anchor=NW) 
        if remain == 0:
            canvas.delete(ALL)
        else:
            _timer = canvas.after(1000, lambda: (canvas.delete(cdtext), cdtimerr()))
    
    root = Tk()
    root.geometry('1024x768')
    canvas = Canvas(root)
    canvas.pack(expand=1, fill=BOTH)
    _timer = canvas.after(0, cdtimerr)
    Button(root, text='Cancel', command=lambda: canvas.after_cancel(_timer)).pack()
    root.mainloop()
    

