python tkinter canvas display image

Let's take a look at the description of the method first

create_image(position, **options) [#]
Draws an image on the canvas.

position
Image position, given as two coordinates.
**options
Image options.
activeimage=
anchor=
Where to place the image relative to the given position. Default is CENTER.
disabledimage=
image=
The image object. This should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL PhotoImage). The application must keep a reference to the image object.
state=
Item state. One of NORMAL, DISABLED, or HIDDEN.
tags=
A tag to attach to this item, or a tuple containing multiple tags.
Returns:
The item id.

There are two important points to note about images, one is the format, and the second is to keep referring to
The image object. This should be a

1.This should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL PhotoImage).
2.The application must keep a reference to the image object.

So the code should be written like this and the variable im should be a global variable

image = Image.open("img.jpg")  
im = ImageTk.PhotoImage(image)  

canvas.create_image(300,50,image = im)  

But what if I just want to call it in a method?
Then you can declare global variables in advance

image = None
im = None

Then use global in the method to declare the variable as a global variable
, namely :

def method():
    global image
    global im
    image = Image.open("img.jpg")  
    im = ImageTk.PhotoImage(image)  
    ...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325848885&siteId=291194637