如何在 tkinter 中使用图像作为背景? [英] How to use an image for the background in tkinter?

查看:30
本文介绍了如何在 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()

此代码不起作用.我想导入背景图片.

This code doesn't work. I want to import a background image.

推荐答案

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

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

例如:

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

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

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

注意:如果你在函数内部这样做,请确保保留对图像的引用,否则在函数返回时图像将被垃圾收集器销毁.一种常用的技术是添加一个引用作为标签对象的属性:

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

这篇关于如何在 tkinter 中使用图像作为背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆