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

时间:2017-06-16 17:51:05

标签: python canvas tkinter python-3.5 pillow

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

  

回溯(最近一次呼叫最后一次):
文件“C:\ Users \ SAURAV   DAS \应用程序数据\本地\程序\ Python的\ Python35 \项目\ classify_gui.py”   第29行,在模块中       cv.create_image(0,0,image = photo,anchor ='nw')AttributeError:'NoneType'对象没有属性'create_image'

是否有其他方式我可以浏览图像的路径并显示它,如

  1. 更改浏览图像路径的方法
  2. 或,更改在画布对象中显示图像的方法

    我在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()
    

1 个答案:

答案 0 :(得分:0)

网格管理器中的方法不会返回窗口小部件。 因此,不要将网格方法放在窗口小部件的末尾。 而是在创建窗口小部件后配置网格。

改变这个:

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')