【问题标题】:How to use an image for the background in tkinter?如何在 tkinter 中使用图像作为背景?
【发布时间】:2012-04-26 20:43:43
【问题描述】:
#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()

此代码不起作用。我要导入背景图片。

【问题讨论】:

  • 您的标签是否显示“欢迎!!!!”如果删除图像属性,则为文本?即Label(app, textvariable=labelText, ...)此文本不会显示图像正在显示,因为图像属性优先于文本变量。
  • 我将向 SO 发送提案,以弃用“不工作”一词。它在它诞生的第一天就失去了任何有用的意义。说真的,试着描述为什么你认为它不起作用。
  • 删除了我的答案,因为它没有回答您的实际问题。您应该编辑您的帖子以使其更具体。我还将使用您在评论中发布的链接来制定此问题的答案。 (在这里回答您自己的问题非常好。)

标签: python tkinter


【解决方案1】:

一种简单的方法是使用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)

然后您可以照常在父级中grid 或pack 其他小部件。只需确保先创建背景标签,使其具有较低的堆叠顺序。

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

background_label.image = background_image

【讨论】:

  • 谢谢你,布莱恩。为了让它在我的程序上运行,我必须在最后一行之前添加行 background_label.photo=background。
  • 如何添加带有文本覆盖的背景图像?
  • @PSSolanki:我不知道你所说的 tcl/tk 不是 bg 图像的好朋友是什么意思。确实,它不会自动调整它们的大小,但是这个答案中的技术仍然是向小部件添加背景图像的最佳方法。
  • @bryanoakley 感谢您回答问题 :) 感谢。
【解决方案2】:

用于设置背景图像的 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

【讨论】:

    【解决方案3】:

    你可以用这个:

    root.configure(background='your colour')
    

    例子:-

    import tkinter
    root=tkiner.Tk()
    root.configure(background='pink')
    

    【讨论】:

    • 如何做到这一点不是问题。
    猜你喜欢
    • 2021-09-01
    • 2021-07-12
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2012-07-16
    • 2020-06-02
    相关资源
    最近更新 更多