user4261180 user4261180 - 2 years ago 101
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 = "" #host IP address

master = Tk()

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

def display():

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

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)


master.after(0, display)

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