Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在tkinter中使用图像作为背景?_Python_Tkinter - Fatal编程技术网

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

Python 如何在tkinter中使用图像作为背景?,python,tkinter,Python,Tkinter,要导入图像的代码: #import statements from Tkinter import * import tkMessageBox import tkFont from PIL import ImageTk,Image 这个代码不起作用。我想导入背景图像。一个简单的方法是使用place将图像用作背景图像。这是place非常擅长做的事情 例如: app = Tk() app.title("Welcome") image2 =Image.open('C:\\Users\\adminp\\

要导入图像的代码:

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

这个代码不起作用。我想导入背景图像。

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

例如:

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()
然后,您可以将父窗口中的其他窗口小部件正常地
grid
pack
打包。只需确保先创建背景标签,使其具有较低的堆叠顺序

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

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

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

background_label.image = background_image

您可以使用root.configure(background='your color')示例:-
import tkinter root=tkiner.Tk()root.configure(background='pink')

如果删除图像属性,标签是否显示“Wecome!!!!”文本?i、 e.
Label(app,textvariable=labelText,…)
由于图像属性优先于textvariable,因此在显示图像时,此文本不会显示。我将向SO发送一份建议,反对使用术语“不工作”。它诞生的第一天就失去了任何有用的意义。说真的,试着描述一下为什么你认为它不起作用。删除了我的答案,因为它没有回答你的实际问题。你应该编辑你的文章,使它更具体。我也会使用你在评论中发布的链接来为这个问题制定答案。(在这里回答你自己的问题很好。)谢谢你,布莱恩。为了让它在我的程序中运行,我必须在最后一行之前添加一行
background\u label.photo=background
。如何添加带有文本覆盖的背景图像?如何做不是问题。
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