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


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

示例

在此示例中,我们将在画布小部件中使用 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="./tutorialspoint.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()

输出

现在,执行以上代码以显示一个窗口,其中包含一个带有一定文本的背景图像。

更新于: 16-4-2021

2 千次观看

启动您的职业生涯

获得认证,完成课程

开始
广告
© . All rights reserved.