python-3.xtkinterpython-imaging-librarytkinter-canvastkinter-menu

tkinter doesn't open image via function


Tkinter doesn't open the image. We can ask the opening incorrectly, we need help. I need it to open the image through the menu. be sure to use pil, as the image can be anything. There are no errors in the syntax. Thank you = )

from tkinter import Tk, Frame, Menu, Canvas, PhotoImage
import easygui
from PIL import Image, ImageFilter, ImageTk

def input_file():
    a = easygui.fileopenbox(filetypes=["*.jpg"])
    original = Image.open(a)
    original = original.resize((799, 799), Image.ANTIALIAS)
    photoimg = ImageTk.PhotoImage(original)
    canvas = Canvas(root, width=799, height=799)
    imagesprite = canvas.create_image(10, 10,anchor='nw', image=photoimg)
    canvas.pack()
    return (imagesprite)

root = Tk()
root.title("Sputnikeca")
#root.iconbitmap('путь к иконке')
root.geometry("800x800+0+0")

my_menu = Menu(root)
root.config(menu=my_menu)

# Create a menu item

file_menu = Menu(my_menu)
my_menu.add_cascade(label = "Файл", menu=file_menu)
file_menu.add_command(label = "Импорт...", command=input_file())
file_menu.add_separator()
file_menu.add_command(label = "Выход", command=root.quit)

root.mainloop()

Solution

  • Here is what you have to do to solve the issue:

    def input_file():
        global photoimg #keeping a reference
        a = easygui.fileopenbox(filetypes=["*.jpg"])
        original = Image.open(a).resize((799, 799), Image.ANTIALIAS) #calling it all in one line
        photoimg = ImageTk.PhotoImage(original)
        canvas = Canvas(root, width=799, height=799)
        imagesprite = canvas.create_image(10, 10,anchor='nw', image=photoimg)
        canvas.pack()
        return imagesprite
    

    and then later remove the () around your function:

    file_menu.add_command(label = "Импорт...", command=input_file)
    

    What is being done?

    Hope this helped you solve the error, do let me know if any doubts.

    Cheers