I'm using TkInter
to write a GUI that will contain an image and a few buttons in a panel next to the image.
I started by writing a script that would allow me to visualize an image, and it works just fine:
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
from PIL import Image, ImageTk
window = Tkinter.Tk()
window.title("Test GUI")
window.geometry("640x478")
window.configure(background='grey')
window.grid()
img = ImageTk.PhotoImage(Image.open('./test.jpg'))
canvas = Tkinter.Canvas(window, width=640, height=478, bg='white')
canvas.create_image(0,0,anchor='nw',image=img)
canvas.grid(column=0,row=0)
window.mainloop()
I then tried to rewrite the above code as a class, to implement some event-handling functions. However, the same exact code written in the class initialization function will not visualize the image.
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
from PIL import Image, ImageTk
class showImageGUI(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# the grid layout manager is a simple grid
# where you put your widgets
self.grid()
img = ImageTk.PhotoImage(Image.open('./test.jpg'))
canvas = Tkinter.Canvas(self, width=640, height=478, bg='white')
canvas.create_image(0,0,anchor='nw',image=img)
canvas.grid(column=0,row=0)
if __name__ == "__main__":
app = showImageGUI(None)
app.title('Test GUI')
# event-driven programming: the program will
# loop forever doing nothing but wait for events
# and only react when it receives an event
app.mainloop()
The only difference between the two is:
- In the script implementation I assign the parent of the
canvas
widget to be the wholewindow
. - In the class implementation I assign the parent of the
canvas
widget to be theself
variable for the whole app.
Can someone please explain me why is this breaking the code / how to solve it?