如何在 tkinter 中使用图像作为背景?

tkinter 中的背景图像用途广泛,因为该功能可用于制作 3D、2D 游戏、屏幕保护程序、桌面可视化软件等。Tkinter canvas 用于在应用程序中处理所有这些功能。

示范

create_image() 在此示例中,我们将使用画布小部件中的方法添加背景图像。

#Import the required library
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
#Create an instance of tkinter window
win= Tk()
#Define the geometry of the window
win.geometry("750x650")
#Load the image
bg= ImageTk.PhotoImage(file="./nhooo.png")
#Create a canvas
canvas= Canvas(win,width= 400, height= 200)
canvas.pack(expand=True, fill= BOTH)
#Add the image in the canvas
canvas.create_image(0,0,image=bg, anchor="nw")
#Add a text in canvas
canvas.create_text(310,550,text="</Hello,Devs!_", font= ('Courier 45 bold'))
win.mainloop()
输出结果

现在,执行上面的代码来显示一个包含带有一些文本的背景图像的窗口。