简体   繁体   English

如何在 tkinter 中正确导入图像到界面

[英]How to correctly import image to interface in tkinter

I am making a photo booth in python.我正在用python制作一个照相亭。 I am using tkinter to do that:我正在使用 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()

But when I start this script an error appears:但是当我启动这个脚本时会出现一个错误:

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

Image is in the same directory as the script and I am using Raspberry Pi 4B 4GB RAM图像与脚本位于同一目录中,我使用的是 Raspberry Pi 4B 4GB RAM

Please Help!请帮忙!

i ran your script and it works perfectly.我运行了你的脚本,它运行得很好。 I don't know if you have multiple tkinter windows in your project but if this the case, use render= ImageTk.PhotoImage(master=tf,image = load) instead of render = ImageTk.PhotoImage(load) .我不知道您的项目中是否有多个 tkinter 窗口,但如果是这种情况,请使用render= ImageTk.PhotoImage(master=tf,image = load)而不是render = ImageTk.PhotoImage(load) This will solve the issue.这将解决问题。 If you don't have multiple windows, try to create your render variable before creating your PhotoImage like this如果您没有多个窗口,请在像这样创建 PhotoImage 之前尝试创建渲染变量

render = 0
render = ImageTk.PhotoImage(load)

I don't know why this work but i solved similar issues with this sevral times.我不知道为什么这项工作,但我解决了这几次类似的问题。 I hope one of my solutions will help you.我希望我的解决方案之一可以帮助您。

Well... I forgot to add嗯...我忘了补充

tf.mainloop()

At the end of script在脚本结束时

Thanks for your help!谢谢你的帮助!

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

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