user4261180 user4261180 - 1 year ago 70
Python Question

How to prevent text overlap on tkinter canvas

This is a simple program designed to grab server latency, project it, and refresh it on a small canvas, however I am unable to find a way to find a way to prevent text overlap, and the new ping remains superimposed over the old ping.

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")

master.after(100, display)

#time.sleep(1)
#canvas.delete(text)
#canvas.update()
print("iteration")

master.after(0, display)
master.mainloop()

Answer Source

Don't create a new text item every time. Instead, just change the text of the old item.

canvas.itemconfigure(text, text=new_latency)

Your other option is to delete the old item before creating the new item, but it's better just to reuse the old item.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download