I wrote my first Tkinter app that contains a button which, on clicking, is supposed to display an image in a canvas:
import tkinter as tk
from PIL import Image, ImageTk
import numpy as np
from itertools import cycle
import helpers
class App():
def __init__(self, master):
frame = tk.Frame(master)
frame.pack()
self.canvas = tk.Canvas(width=500, height=500)
self.canvas.pack()
self.load_button = tk.Button(
frame, text="Load image", command=self.load_image)
self.load_button.pack(side=tk.LEFT)
self.img_no = 0
def load_image(self):
stack = helpers.read_image_sequence("path")
data = stack[self.img_no]
im = Image.fromarray(data)
im = im.resize((200, 200))
photo = ImageTk.PhotoImage(image=im)
self.canvas.create_image(0, 0, image=photo, anchor=tk.NW)
self.pack()
root = tk.Tk()
app = App(root)
root.mainloop()
After clicking the button, the image won't appear unless I add self.pack()
at the end of its function. This works but causes the error:
AttributeError: 'App' object has no attribute 'pack'
Apparently this is because my App() class doesn't inherit from a suitable parent. How to do this properly? I tried tk.Tk
as parent:
class App(tk.Tk):
def __init__(self, master):
super().__init__()
Which results in the error:
AttributeError: '_tkinter.tkapp' object has no attribute 'pack'
And I tried tk.Frame
which doesn't result in any error, but the image doesn't show either! What am I missing..? Using Python 3.5.