如何在 Tkinter 窗口中绘制图像?
要使用 Tkinter 和其他 Python 包处理图像,我们通常会参考在 Python 中使用 Pillow 包或 PIL。它提供了一种在程序中加载和处理图像的方式,无论我们何时何地需要。最初,我们将图像转换为 PhotoImage 对象的一个实例,这样就可以在许多用例中进一步使用图像。此外,Tkinter 中的画布小部件有助于在 Tkinter 应用程序中绘制图像,我们可以使用 create_image(x,y, image_file) 方法在特定应用程序中显示图像。
示例
#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()
#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))
#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)
win.mainloop()输出
运行以上代码将显示一个窗口,其中会在画布小部件中显示一张图像。
为了替换或更改给定输出中的图像文件,只需在 Image.Open(文件名) 方法中导入该图像即可。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP