tkinter canvas image not displaying

后端 未结 2 674
忘掉有多难
忘掉有多难 2021-02-19 10:20

I have a simple canvas being created in a function, and i would like an image displayed on the canvas.

def start(root):
    startframe = tkinter.Frame(root)
             


        
相关标签:
2条回答
  • 2021-02-19 10:20
    1. Escape backslashes in path string correctly. (or use r'raw string literal').

    2. Prevent PhotoImage object being garbage collected.

    3. specify the filename using file=... option.


    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

    The two statements one = ... and root.one = one can be merged into one statement:

        root.one = one = tkinter.PhotoImage(r'images\one.gif')
    
    0 讨论(0)
  • 2021-02-19 10:27

    How about canvas.update()? I was suffering a similar problem. I am using grid, so instead of .pack I needed to use .update.

    0 讨论(0)
提交回复
热议问题