Tkinter canvas image not showing

I have a simple canvas being created in a function and I would like the image to be displayed on the canvas.

def start(root):
    startframe = tkinter.Frame(root)
    canvas = tkinter.Canvas(startframe,width=1280,height=720)

    startframe.pack()
    canvas.pack()

    one = tkinter.PhotoImage('images\one.gif')
    canvas.create_image((0,0),image=one,anchor='nw')

      

when i run the code i get a blank 1280x720 window, no image.

I have looked at the following website: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm but I don’t understand how to apply their example to my situation (I don’t know what create a link or how to create a link if that's my problem). I also looked at some stack overflow problems, but they didn't help either.

+3


source to share


1 answer


  • Ignore backslashes in path string correctly. (or use r'raw string literal'

    ).

  • Prevent collection of the PhotoImage object.

  • specify the file name using the parameter file=...

    .


def start(root):
    startframe = tkinter.Frame(root)
    canvas = tkinter.Canvas(startframe,width=1280,height=720)

    startframe.pack()
    canvas.pack()

    # Escape / raw string literal
    one = tkinter.PhotoImage(file=r'images\one.gif')
    root.one = one  # to prevent the image garbage collected.
    canvas.create_image((0,0), image=one, anchor='nw')

      



UPDATE

Two operators one = ...

and root.one = one

can be combined into one operator:

    root.one = one = tkinter.PhotoImage(r'images\one.gif')

      

+10


source







All Articles