Python Forum

Full Version: Updating tkinter text
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there any possible way to update the canvas text with the tkinter canvas? I have a variable with the number that has to keep updating and a variable with the text, including the number. I have a command that automatically updates the number upon the click of a button. How do I make the canvas text updating?
First, why are you using a Canvas? If you have to have it on a canvas, use create_window to put a Label on the canvas and update it.
A quick example updating canvas text

import tkinter as tk

import time

def get_time(arg, canvas, var):
    show = time.strftime(f'%I:%M:%S %P')
    canvas.itemconfig(var, text=show)
    arg.after(1000, lambda: get_time(arg, canvas, var))

root = tk.Tk()

canvas = tk.Canvas(root, width=600, height=500, bg='antiquewhite')
show = time.strftime(f'%I:%M:%S %P')
var = canvas.create_text(300,100, text=show, fill='blue', font=('serif', 20, 'bold'))
canvas.pack()

root.after(1000, lambda: get_time(root, canvas, var))
root.mainloop()
It works also like this:
import tkinter as tk

import time

def get_time(canvas):
    show = time.strftime(f'%I:%M:%S %P')
    canvas.itemconfig(var, text=show)
    canvas.after(1000, get_time, canvas)

root = tk.Tk()

canvas = tk.Canvas(root, width=600, height=500, bg='antiquewhite')
show = time.strftime(f'%I:%M:%S %P')
var = canvas.create_text(300,100, text=show, fill='blue', font=('serif', 20, 'bold'))
canvas.pack()

get_time(canvas)

root.mainloop()
Greetings wuf Smile
(Nov-24-2022, 07:22 PM)wuf Wrote: [ -> ]It works also like this:
import tkinter as tk

import time

def get_time(canvas):
    show = time.strftime(f'%I:%M:%S %P')
    canvas.itemconfig(var, text=show)
    canvas.after(1000, get_time, canvas)

root = tk.Tk()

canvas = tk.Canvas(root, width=600, height=500, bg='antiquewhite')
show = time.strftime(f'%I:%M:%S %P')
var = canvas.create_text(300,100, text=show, fill='blue', font=('serif', 20, 'bold'))
canvas.pack()

get_time(canvas)

root.mainloop()
Greetings wuf Smile
I tried running the code.
Error:
Traceback (most recent call last): File "C:\Users\Wannes\canvas update.py", line 13, in <module> show = time.strftime(f'%I:%M:%S %P') ValueError: Invalid format string
A couple of problems. First off, the call is wrong. You need to pass a time string and a format string.
Quote:classmethod datetime.strptime(date_string, format)
Return a datetime corresponding to date_string, parsed according to format.
Once that is fixed, there is still an error in the format string. Here are all the different codes you can use in the format string.

https://docs.python.org/3/library/dateti...e-behavior