如何在Python tkinter画布上绘制png图像?
为了在tkinter中使用图像,Python提供了PIL或Pillow工具包。它具有许多内置函数,可以用来操作不同格式的图像。
要在画布小部件中打开图像,我们必须使用 create_image(x, y, image, **options) 构造函数。当我们将图像值传递给构造函数时,它将在画布中显示该图像。
示例
# 导入所需库
from tkinter import *
from PIL import Image, ImageTk
# 创建tkinter框架或窗口的实例
win=Tk()
# 设置窗口的大小
win.geometry("700x600")
# 创建一个画布小部件
canvas=Canvas(win, width=700, height=600)
canvas.pack()
# 加载图像
img=ImageTk.PhotoImage(file="Monalisa.png")
# 在画布中添加图像
canvas.create_image(350, 400, image=img, anchor="center")
win.mainloop()
输出
运行上述代码将显示一个窗口,其中包含画布中的图像。