【问题标题】:Python Tkinter - Photo as backgroundPython Tkinter - 照片作为背景
【发布时间】:2018-10-15 11:14:07
【问题描述】:

这是一个学校项目,所以我有点想了解我在做什么。

我想添加一张照片,例如以“teletubbies.jpg”为背景的照片。我不知道如何做到这一点以及它是如何工作的,现在已经搜索了几个小时并且渴望找到答案:$

这是我现在拥有的代码:

from tkinter import *

from tkinter.messagebox import showinfo

def clicked():
    bericht = 'Test for stackflow!',
    showinfo(title='popup', message=bericht)

def clicked1():
    bericht = 'Test for stackflow'
    showinfo(title='popup', message=bericht)

root = Tk()

label = Label(master=root,
              text='This is a test for stackflow',
              background='black',
              foreground='white',
              height = 2
              )
label.pack()

button2 = Button(master=root, text='Klik hier voor het beheerportaal', command=clicked, fg='red')
button2.pack(side=BOTTOM,pady=10)

button1 = Button(master=root, text='Klik hier voor het klantportaal', command=clicked1)
button1.pack(side=TOP,pady=10)

entry = Entry(master=root)
entry.pack(padx=10, pady = 10)

root.configure(background='black')
root.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    如果您有 .gif.pgm/ppm 文件,您可以使用 Tkinter PhotoImage 类加载您的图像并将其作为标签的背景:

    backgroundImage = PhotoImage(file = <yourFilePath>)
    label = Label(master=root,
                  image = backgroundImage,
                  text='This is a test for stackflow',
                  height = 2
                  )
    label.place(x=0, y=0, relwidth=1, relheight=1)
    

    这会将您的图像作为标签中的背景。

    对于其他图像格式,您可以使用Python Image Library

    【讨论】:

    • 我试过这样做,但是当我尝试打开一个 .gif 文件时,它给出了错误:_tkinter.TclError:无法识别图像文件“teletubbies.gif”中的数据因为我相信也就是说,当文件与图像在同一目录中时,我不必指定图像文件的路径,只需名称即可
    • 是的,你是对的,你不应该指定完整路径,但错误表明你的图像不可读。你确定图片是gif吗?您还有其他图片可以尝试吗?
    • 听起来像是实际文件而不是路径。在这里可能会有所帮助stackoverflow.com/questions/15718663/…
    • 你是英雄,非常感谢。我认为我尝试的图像不是 .gif 文件,即使扩展名是这样说的,有点奇怪:P。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2020-02-06
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多