What I want is that when the "Open" button is pressed a file chooser opens and the image that is chosen get displayed and that the canvas is resized to nicely fit the image. The problem is that when the image has been chosen the canvas does change to the correct size, but the image is not displayed.
This is what I have so far:
class ShowImg(object):
def __init__(self):
self.root = Tk()
# open button
open_button = ttk.Button(self.root, text='Open', command=self.select_file)
open_button.grid(row=0, column=0)
# save button (TODO)
open_button = ttk.Button(self.root, text='Save')
open_button.grid(row=0, column=1)
# image canvas
self.max_dims = (500, 500)
self.canvas = Canvas(self.root, width=self.max_dims[0], height=self.max_dims[1])
self.canvas.grid(row=1, column=0, columnspan=2)
im = Image.fromarray(np.zeros((self.max_dims[1], self.max_dims[0], 3)), 'RGB')
img = ImageTk.PhotoImage(im)
self.img_id = self.canvas.create_image(0, 0, anchor=NW, image=img)
self.root.mainloop()
def select_file(self):
filetypes = (('image files', '*.jpg *.png *.gif *.jpeg *.jfif'), ('All files', '*.*'))
filename = fd.askopenfilename(filetypes=filetypes)
im = Image.open(filename)
im.thumbnail(self.max_dims)
img = ImageTk.PhotoImage(im)
self.canvas.config(width=im.width, height=im.height)
self.canvas.itemconfig(self.img_id, image=img)
if __name__ == '__main__':
ShowImg()