如何解决tkinter无法通过功能打开图像
Tkinter无法打开图像。我们可能会错误地要求开放,我们需要帮助。我需要它来通过菜单打开图像。确保使用pil,因为图像可以是任何东西。语法没有错误。谢谢=)
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()
解决方法
这是您必须解决的问题:
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
,然后再删除函数周围的()
:
file_menu.add_command(label = "Импорт...",command=input_file)
正在做什么?
-
在第一组代码中,im保留了对图像的引用,因此图像不会被python垃圾收集。您可以通过在函数顶部说出
imagesprite.image = photoimg
或global photoimg
来做到这一点。我还按照打开图片的同一行调整了图片的大小,以减少代码。 -
在第二组代码中,我只是删除了
()
,以便在选择菜单项之前不调用(调用)该函数。 -
并且tkinter本身也有一个
filedialogbox
,其作用类似于您的easygui.fileopenbox(filetypes=["*.jpg"])
,请阅读一些文档herefrom tkinter import filedialog a = filedialog.askopenfilename(title='Choose a file',initialdir='C:/',filetypes=(('All Files','*.*'),("JPEG Files",'*.jpeg')))
希望这可以帮助您解决错误,如果有任何疑问,请告诉我。
欢呼
,如果我没记错的话,菜单会在运行应用程序后立即打开,而不是在单击导入按钮时打开。
这是因为您需要将回调传递给add_command,但是您正在调用方法
file_menu.add_command(label = "Import...",command=input_file())
从input_file()中删除()。只需传递input_file。它不会再直接调用该方法。
file_menu.add_command(label = "Import...",command=input_file)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。