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

标签 python tkinter

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image

导入图片代码:

app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)

labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')

label1 = Label(app, image=image1, textvariable=labelText,
               font=("Times New Roman", 24),
               justify=CENTER, height=4, fg="blue")
label1.pack()

app.mainloop()

此代码无效。我想导入背景图片。

最佳答案

一种简单的方法是使用place 将图像用作背景图像。这是 place 非常擅长做的事情。

例如:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

然后您可以像往常一样在父级中网格打包其他小部件。只需确保先创建背景标签,使其具有较低的堆叠顺序即可。

注意:如果您在函数内部执行此操作,请确保保留对图像的引用,否则图像将在函数返回时被垃圾收集器销毁。一种常见的技术是添加引用作为标签对象的属性:

background_label.image = background_image

关于python - 如何在 tkinter 中使用图像作为背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158552/

相关文章:

text - 使用 tk 创建文本编辑器

python - 当按下按钮时,什么也没有发生。甚至没有错误消息

python - Pandas 绘图功能忽略时间序列的时区

python - 对象与字典 : how to organise a data tree?

python - Mongoengine Document对象无法使用from_json更新

python - 如何比较Python中的准确时间和输入时间

python - Tkinter - Python 3.5

python - 在新列中获取具有相似地址的 ID

python - 根据大小分割文件的有效方法

python - 单击时更改按钮外观