简体   繁体   中英

How to correctly import image to interface in tkinter

I am making a photo booth in python. I am using tkinter to do that:

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

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) . This will solve the issue. If you don't have multiple windows, try to create your render variable before creating your PhotoImage like this

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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