the_prole
the_prole

Reputation: 8945

How do I refresh a text object on a canvas using a loop?

I am writing a program that outputs latency onto a canvas and updates the latency every second. The problem is that the canvas also has a background image, and the background image will not show on the canvas until the mainloop() line is reached in which case I can no longer update the latency.

from tkinter import *
from PIL import ImageTk, Image
import subprocess
import time

host = "141.101.115.212" #host IP address

master = Tk()

im = Image.open("image.png")
width, height = im.size
canvas = Canvas(master, width=width, height=height)
canvas.pack()
image = ImageTk.PhotoImage(file="image.png")
canvas.create_image(0, 0, image=image, anchor=NW)


def display():
    x = subprocess.Popen(["ping.exe", "141.101.115.212"], stdout=subprocess.PIPE)
    x = str(x.communicate()[0])
    lhs, rhs = x.split("Average = ")
    lhs, rhs = rhs.split("\\", 1)
    print(lhs)

    latency = lhs
    text = canvas.create_text(40, 100, anchor=NW)
    canvas.itemconfig(text, text=latency, width=width)
    canvas.itemconfig(text, font=("courier", 70, "bold"))
    canvas.itemconfig(text, fill="white")

    print("iteration")
    return

while 1 == 1:
    display()
    time.sleep(1)
mainloop()

Upvotes: 1

Views: 13877

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

You should create and configure the text once and loop with an after method. An example that works for me.

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
iptext = canvas.create_text(100, 100, width=100,
                          font=("courier", 15, "bold"))
ips = (t for t in ('111', '222', '333', '444'))
def update_ip():
    try:
        canvas.itemconfigure(iptext, text=next(ips))
        root.after(1000, update_ip)
    except StopIteration:
        pass
update_ip()
root.mainloop()

Consider whether you really want the image and text on a canvas, as opposed to putting both in root or a frame. I believe Canvas text is usually used to label a drawing.

Upvotes: 5

Related Questions