简体   繁体   English

如何将图像作为 tkinter 的背景?

[英]How can I put an image as a background on tkinter?

To change things up, I wanted to put blue wallpaper image as my background on my python script.为了改变它,我想把蓝色壁纸图像作为我的 python 脚本的背景。 Here is the code:这是代码:

from tkinter import *

root = Tk()
root.title("")
root.iconbitmap()
#root.minsize(width=1370, height=800)
#root.maxsize(width=1370, height=800)

background = PhotoImage(file="background.jpeg")
background_label = Label(root,image=background)
background_label.place(x=0,y=0,relwidth=1,relheight=1)

root.mainloop()

However, when I run this code this error pops up:但是,当我运行此代码时,会弹出此错误:

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 4006, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "background.jpeg"

Does anyone know how to solve this problem?有谁知道如何解决这个问题?

You Can Use ImageTk:您可以使用 ImageTk:

from PIL import ImageTk
from tkinter import *

root = Tk()
root.title("")
root.iconbitmap()

background = ImageTk.PhotoImage(file="background.jpeg")
background_label = Label(root,image=background)
background_label.place(x=0,y=0,relwidth=1,relheight=1)

root.mainloop()

Hope It Helps:D希望它有帮助:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM