Home>

I want to display an image with the tkinter module, but I can't do it well.
Moreover, there was no error, just the canvas came out and the image was not displayed.

Corresponding source code
from tkinter import *
tk = Tk ()
tk.title ("1 + 1 = 3")
tk.resizable (0,0) # Determine the size of the window.
tk.wm_attributes ("-topmost", 1) # Bring the game screen to the top
canvas = Canvas (tk, width = 1430, height = 800, bd = 0, highlightthickness = 0)
canvas.pack ()
tk.update ()
hai = PhotoImage ("/ Users/username/Desktop/python/background.gif")
canvas.create_image (0,0, anchor = NW, image = hai)
What I tried

I changed the location of PhotoImage to /Users/username/background.gif, but it didn't change.
I confirmed it with the os module, so I think there is no doubt.
Also, I tried to name the image in English, but it didn't change.

Supplementary information (FW/tool version, etc.)

I am using IDLE of python and the version is the latest.
Also, the personal computer uses a macbook.

  • Answer # 1

    The drawing is reflected when the tkinter event loop is running, so
    tk.mainloop ()Try to call at the end

    Also, when writing the entire code inside a function
    Also note the lifetime of the variable that stores the PhotoImage.
    It is destroyed by the destructor and there is no error
    The image may not be displayed either, so you need to keep it somewhere.