如何使用从文件浏览器获取的路径在 tkinter 中的 canvas 对象中显示图像

How to display an image in a canvas object in tkinter using the path obtained from file browser

create_image 命令显示我正在浏览图像并传递给命令的图像参数的路径错误,

Traceback (most recent call last):
File "C:\Users\SAURAV DAS\AppData\Local\Programs\Python\Python35\projects\classify_gui.py", line 29,
in module cv.create_image(0, 0, image=photo, anchor='nw') AttributeError: 'NoneType' object has no attribute 'create_image'

有没有其他方法可以浏览图像的路径并显示它,如

  1. 更改图片路径浏览方式
  2. 或者,改变在canvas对象中显示图像的方法

    我在 Windows 10 上使用 Python 3.5。我已经安装了代码中提到的所有先决条件库。我使用的所有图像都作为我的项目在工作目录中。
    请帮助...

    import sys
    import tkinter as tk
    from PIL import Image,ImageTk,ImageFilter,ImageOps
    
    
    global fname
    fname = "images.png"
    
    
    def browse_file():
        fname = tk.filedialog.askopenfilename(filetypes=(("Bitmap files", "*.bmp"), ("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("All files", "*")))
        print(fname)
        return
    
    def classify_obj():
        print("In Development")
        return
    
    
    root = tk.Tk()
    root.wm_title("Classify Image")
    
    broButton = tk.Button(master=root, text='Browse', height=2, width=8, command=browse_file).grid(row=0, column=0, padx=2, pady=2)
    
    frame1 = tk.Frame(root, width=500, height=400, bd=2).grid(row=1, column=0)
    im = Image.open(fname)
    photo = ImageTk.PhotoImage(im)
    cv = tk.Canvas(frame1, height=390, width=490, background="white", bd=1, relief=tk.RAISED).grid(row=1,column=0)
    cv.create_image(0, 0, image=photo, anchor='nw')
    
    claButton = tk.Button(master=root, text='Classify', height=2, width=10, command=classify_obj).grid(row=0, column=1, padx=2, pady=2)
    
    frame2 = tk.Frame(root, width=500, height=400, bd=1).grid(row=1, column=1)
    cv = tk.Canvas(frame2, height=390, width=490, bd=2, relief=tk.SUNKEN).grid(row=1,column=1)
    
    tk.mainloop()
    

网格管理器中的方法不会 return 小部件。 所以不要将网格方法放在小部件的末尾。 而是在创建小部件后配置网格。

改变这个:

cv = tk.Canvas(frame1, height=390, width=490, background="white", bd=1, relief=tk.RAISED).grid(row=1,column=0)
cv.create_image(0, 0, image=photo, anchor='nw')

为此:

cv = tk.Canvas(frame1, height=390, width=490, background="white", bd=1, relief=tk.RAISED)
cv.grid(row=1,column=0)
cv.create_image(0, 0, image=photo, anchor='nw')