我正在编写一个程序,将延迟输出到画布上并每秒更新延迟。问题是画布还有一个背景图像,在到达mainloop()
行之前,背景图像不会显示在画布上,在这种情况下,我无法再更新延迟。
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()
答案 0 :(得分:3)
您应该创建并配置一次文本并使用after方法循环。一个适合我的例子。
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()
考虑您是否真的想要画布上的图像和文本,而不是将它们放在根或框架中。我相信Canvas文本通常用于标注绘图。