Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter canvas image is not displayed in class

Tags:

python

tkinter

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()
like image 930
konovalov100 Avatar asked May 30 '13 21:05

konovalov100


1 Answers

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')
like image 147
A. Rodas Avatar answered Oct 12 '22 08:10

A. Rodas