6
votes

I am trying to display an image in python using the tkinter canvas option. However, if I input it in a class, like below, it doesn't give an error but also doesn't show my image. The buttons are displayed correctly though. Also, if I take the code for generating this image out of the class it works correctly. I can't seem to find out what the problem is.

import Tkinter as tk
from Tkinter import *

class Board(tk.Frame):
    def __init__(self,parent):

        frame = Frame(parent)
        frame.pack()
        tk.Frame.__init__(self,parent)

        frame2 = Frame(frame)
        frame2.pack()

        c=Canvas(frame2)
        c.pack(expand=YES,fill=BOTH)
        background=PhotoImage(file='Board.gif')
        c.create_image(100,100,image=background,anchor='nw')

        button = Button(frame, text="Next turn", command=self.next_turn)
        button.pack()

        button = Button(frame, text="Roll the dice", command=self.roll)
        button.pack()

        ....

root = Tk()
board = Board(root)
board.pack()
root.mainloop()
1
why are you doing both import Tkinter as tk AND from Tkinter import *? - Rushy Panchal
My teacher told me to do that, to be sure everything got imported or something. I know it's not nessecary, but now there are some lines which have tk.'something' and if I just delete the tk. my program freaks out. You think that could be the problem? - konovalov100
That's probably because of the tk.Frame.__init__(self,parent) and the class Board(tk.Frame). You can change that to Frame.__init__(self,parent) and class Board(Frame), which should work, though I'm not sure why you're directly calling an __init__ method; I don't see what purpose that Frame serves either because you're not keeping reference to it. - Rushy Panchal

1 Answers

7
votes

You have to keep a reference to the PhotoImage. This is just and example (you can also use self.background instead of c.background):

    c = Canvas(frame2)
    c.pack(expand=YES,fill=BOTH)
    c.background = PhotoImage(file='Board.gif')
    c.create_image(100,100,image=c.background,anchor='nw')