Explain how to display an image with the tkinter function. It also supports jpg.
■Example using tkinter function
You can display jpg by using "ImageTk".
import tkinter as tk
from PIL import Image, ImageTk
app = tk.Tk()
img = Image.open('test.jpg') # Open an image file and get file information. "text.jpg" is set arbitrarily
tk_img = ImageTk.PhotoImage(img)
img_width, img_height = img.size
create_image( X-axis , Y-axis , anchor=Display type , image=image name)
anchar is below.
0 of x 0 of y
"NW" image left image top
"W" image left image center
"N" image center image top
"SE" image right image bottom
"S" image center image bottom
"E" image right image center
"CENTER" image center image center (Default)
■The image will not be displayed if it becomes a function
If you call the image display part as a function, the image will not be displayed as it is.
The reason is that even if the image is displayed once, it is judged that the image information is no longer necessary when the function ends, and it is deleted internally.
As a countermeasure, make the image information a global variable as shown in the red part below, or store the image information outside of def as shown in the blue part.
You only need to write either the red part or the blue part.
import tkinter as tk
from PIL import Image, ImageTk
def draw():
global tk_img # Make the image information a global variable.
img = Image.open('test.jpg')
tk_img = ImageTk.PhotoImage(img)
img_width, img_height = img.size