Example of python tkinter canvas display picture
- 2021-06-28 13:15:13
- OfStack
Let's start with an explanation of this method
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 image, one is the format, and the second is to keep the references constant
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 write 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 ahead of time
image = None
im = None
Then use global in the method to declare the variable as a global variable
That is:
def method():
global image
global im
image = Image.open("img.jpg")
im = ImageTk.PhotoImage(image)
...