Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pillow ImageTk Module

Pillow ImageTk Module

ImageTk is a submodule of the Python image processing library Pillow (a fork of PIL), mainly used to display and process images in Tkinter GUI programs.

ImageTk provides an PhotoImage alternative to the class, supporting more image formats (such as JPEG, PNG), and allowing direct manipulation of image data.

Import method:



from PIL import Image, ImageTk


Core ImageTk Methods

The following table lists the ImageTk The main methods of the module and their functional descriptions:

Method Parameters Return Value Description
ImageTk.PhotoImage() image(PIL.Image object)
 `size`(可选,调整大小)       

 `format`(可选,指定格式) | `PhotoImage` 对象 | 将 PIL.Image 对象转换为 Tkinter 兼容的图像对象 |

| ImageTk.BitmapImage() | file(bitmap file path)
background(background color)
foreground(foreground color) | BitmapImage Object | Load a bitmap (.xbm format) and convert it to a Tkinter image object | | ImageTk.getimage() | photoimage(Tkinter.PhotoImage object) | PIL.Image object | Convert a Tkinter PhotoImage object back to a PIL.Image object |


Basic Usage Example

Displaying an Image

Example

from

PIL

import

Image

,

ImageTk

import

tkinter

as

tk

root

=

tk.

Tk

(

)

Load an image and convert it to Tkinter format

image

=

Image.

open

(

"example.jpg"

)

photo

=

ImageTk.

PhotoImage

(

image

)

Display in a Label

label

=

tk.

Label

(

root

,

image

=

photo

)

label.

pack

(

)

root.

mainloop

(

)

Dynamically update the image

Example

def

update_image

(

)

:

    new_image

=

Image.

open

(

"new_image.jpg"

)

    new_photo

=

ImageTk.

PhotoImage

(

new_image

)

    label.

config

(

image

=

new_photo

)

    label.

image

=

new_photo  

Prevent garbage collection

button

=

tk.

Button

(

root

,

text

=

"Update Image"

,

command

=

update_image

)

button.

pack

(

)


Notes

  1. Memory management: Tkinter's PhotoImage objects need to be referenced for a long time (such as binding to a global variable or widget attribute), otherwise they will be garbage collected and the image will disappear.
  2. Thread Safety: Tkinter and ImageTk operations must be performed in the main thread.
  3. Format support:ImageTk.PhotoImage Supports all formats that Pillow can decode (such as PNG, JPEG), but BitmapImage only supports .xbm bitmaps.

Common questions

Image not displayed

Performance optimization