How to display an image with tkinter(python) Supports jpg



Python
library
pip

MeCab

numpy
digitize

mgrid

pad

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

scipy
interpolate
tkinter
postscript

image display

frame, grid

other
linear interpolation

OpenAI gym
CartPole-v0


Release date:2023/7/30         

In Japanese


■Description of tkinter functions

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

canvas = tk.Canvas(app, width=img_width, height=img_height)        # Generate image display area
canvas.pack()
canvas.create_image(0, 0 , anchor = tk.NW, image=tk_img)        # image display

app.mainloop()


The results are as follows.


<Contents of create_image>

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

    canvas = tk.Canvas(app, width=img_width, height=img_height)        
    canvas.pack()
    canvas.create_image(0, 0 , anchor = tk.NW , image=tk_img)        
    image.append(tk_img)

app = tk.Tk()
image =[]
draw()

app.mainloop()










List of related articles



Python
library
pip

MeCab

numpy
digitize

mgrid

pad

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

scipy
interpolate
tkinter
postscript

image display

frame, grid

other
linear interpolation

OpenAI gym
CartPole-v0