0

I am trying to create a GUI in which I can process images, so I have to change the default image to the one chosen by the browse button. The default image disappears but the new image doesn't appear. Help Please! Here is my code:

from Tkinter import *
from tkFileDialog import askopenfilename
import cv2

class Browse_image :
    def __init__ (self,master) :

        frame = Frame(master)
        frame.grid(sticky=W+E+N+S)
        self.browse = Button(frame, text="Browse", command = lambda: self.browseim())
        self.browse.grid(row=13, columnspan=2)
        self.check = Checkbutton(frame, text="On/Off")
        self.check.grid(row=0)
        self.maxval = Scale(frame, from_=0, to=100, orient=HORIZONTAL)
        self.maxval.grid(row=1,columnspan=2)
        self.minval = Scale(frame, from_=0, to=100, orient=HORIZONTAL)
        self.minval.grid(row=2,columnspan=2)
        self.photo = PhotoImage(file="browse.png")
        self.label = Label(frame, image=self.photo)
        self.label.grid(row=3,rowspan=10)

    def browseim(self):
        path = askopenfilename(filetypes=(("png files","*.png"),("jpeg files","*.jpeg")) )
        if path:
            self.photo = PhotoImage(path)                        
            self.label.configure(image = self.photo)
            #self.label.image = self.photo
            #self.label.grid(row=3,rowspan=10)


root= Tk()
b= Browse_image(root)
root.mainloop()
Parviz Karimli
  • 1,247
  • 1
  • 14
  • 26
Dorra Hadrich
  • 79
  • 1
  • 2
  • 12

1 Answers1

0

Change self.photo = PhotoImage(path) to self.photo = PhotoImage(file=path). The file parameter is required to define an image path in PhotoImage class.

Parviz Karimli
  • 1,247
  • 1
  • 14
  • 26
  • Thanks! But now it shows an other error: "TclError: couldn't recognize data in image file" – Dorra Hadrich Sep 11 '16 at 13:56
  • This error message is usually raised when using an unsupported image type. Are you sure you are using a correct PNG file? Because `PhotoImage` does not support some image file types e.g. JPG, ICO. But it does support PNG. – Parviz Karimli Sep 11 '16 at 14:11
  • thanks a lot! you're right: it only supports PNG files. – Dorra Hadrich Sep 11 '16 at 14:26
  • If I want to put an other image type I should use: from PIL import Image, ImageTk img = Image.open(path) self.photo = ImageTk.PhotoImage(img) self.label.configure(image = self.photo) – Dorra Hadrich Sep 11 '16 at 14:45
  • It supports GIF files too. And yes, as in the [source](http://effbot.org/tkinterbook/photoimage.htm) I have mentioned above in my answer: "If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects". – Parviz Karimli Sep 11 '16 at 15:17