Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - tkinter canvas image is not displayed in class

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...