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()
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?
In the first set of code im keeping a reference to the image so the image is not garbage collected by python. You can do so either by saying imagesprite.image = photoimg
or global photoimg
on top of the function. I also resized the image in the same line that I opened the image, to reduce codes.
And in the second set of codes, im just removing ()
so that the function is not called(invoked) before choosing the menu item.
And also tkinter itself has a filedialogbox
that works like your easygui.fileopenbox(filetypes=["*.jpg"])
, read some docs here
from tkinter import filedialog
a = filedialog.askopenfilename(title='Choose a file',initialdir='C:/',filetypes=(('All Files','*.*'),("JPEG
Files",'*.jpeg')))
Hope this helped you solve the error, do let me know if any doubts.
Cheers