问题描述
所以我在 Tkinter 窗口中使用画布显示图像。现在我有一个计算某些参数的按钮,我希望它在图像上动态显示。所以基本上每次计算后,注释都应该更改为新参数。
例如考虑到我正在计算列尺寸,并且在每次计算之后,我必须在我的 Tkinter 窗口中显示列图像的各个侧面标记的尺寸。
那么是否可以动态注释图像,如果不能,还有其他方法可以执行此任务吗?
解决方法
看看下面的例子
from tkinter import *
from PIL import Image,ImageTk
import random
def annotate():
annotation=str(random.randint(1000,9999))
canvas.itemconfig(annotation_text,text=annotation)
root=Tk()
canvas=Canvas(root)
canvas.pack(fill='both',expand=True)
image=Image.open('example.png')
image=ImageTk.PhotoImage(image.resize((300,300)))
canvas.create_image(150,150,image=image)
annotation_text=canvas.create_text(50,50,text='')
button=Button(root,text='Annotate',command=annotate)
button.pack()
root.mainloop()
您可以使用 itemconfig
方法来配置文本。上面的示例将在 (50,50)
处用一个随机整数在单击按钮时注释图像。