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

use*_*381 13 python tkinter

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image
Run Code Online (Sandbox Code Playgroud)

导入图片的代码:

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()
Run Code Online (Sandbox Code Playgroud)

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

Bry*_*ley 20

一种简单的方法是使用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)
Run Code Online (Sandbox Code Playgroud)

您可以正常使用父级gridpack其他小部件.只需确保首先创建背景标签,使其具有较低的堆叠顺序.

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

background_label.image = background_image
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,布莱恩。为了让它在我的程序上工作,我必须在最后一行之前添加一行 `background_label.photo=background`。 (2认同)

小智 5

用于设置背景图像的 Python 3 的简单 tkinter 代码。

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop
Run Code Online (Sandbox Code Playgroud)