如何将图像作为背景放在 tkinter 上?
How can I put an image as a background on tkinter?
为了改变现状,我想在我的 python 脚本中使用蓝色墙纸图像作为背景。这是代码:
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()
但是,当我 运行 此代码时,会弹出此错误:
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"
有谁知道如何解决这个问题?
您可以使用 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()
希望对你有帮助:D
为了改变现状,我想在我的 python 脚本中使用蓝色墙纸图像作为背景。这是代码:
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()
但是,当我 运行 此代码时,会弹出此错误:
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"
有谁知道如何解决这个问题?
您可以使用 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()
希望对你有帮助:D