[英]How to correctly import image to interface in tkinter
我正在用python制作一个照相亭。 我正在使用 tkinter 来做到这一点:
from tkinter import *
from tkinter import font
import os
from PIL import Image
from PIL import ImageTk
load = Image.open("./image1.jpg")
def startCallBack():
tf = Tk()
render = ImageTk.PhotoImage(load)
img = Label(tf, image=render)
img.image = render
img.pack()
root.destroy()
tf.mainloop()
root = Tk()
appHighlightFont = font.Font(family='Helvetica', size=48, weight='bold')
label=Label(root, text='PHOTO BOOTH', font=appHighlightFont)
btn = Button( root, text ="START", command = startCallBack )
label.place(relx=0.5, rely=0.4,anchor="center")
btn.place(relx=0.5, rely=0.6,anchor="center")
root.mainloop()
但是当我启动这个脚本时会出现一个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "photobooth.py", line 10, in startCallBack
img = Label(tf, image=render)
File "/usr/lib/python3.7/tkinter/__init__.py", line 2766, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "/usr/lib/python3.7/tkinter/__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist
图像与脚本位于同一目录中,我使用的是 Raspberry Pi 4B 4GB RAM
请帮忙!
我运行了你的脚本,它运行得很好。 我不知道您的项目中是否有多个 tkinter 窗口,但如果是这种情况,请使用render= ImageTk.PhotoImage(master=tf,image = load)
而不是render = ImageTk.PhotoImage(load)
。 这将解决问题。 如果您没有多个窗口,请在像这样创建 PhotoImage 之前尝试创建渲染变量
render = 0
render = ImageTk.PhotoImage(load)
我不知道为什么这项工作,但我解决了这几次类似的问题。 我希望我的解决方案之一可以帮助您。
嗯...我忘了补充
tf.mainloop()
在脚本结束时
谢谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.