The Tkinter PhotoImage Class
The PhotoImage class is used to display images (either grayscale or true color images) in labels, buttons, canvases, and text widgets.
When to use the PhotoImage Class
You can use the PhotoImage class whenever you need to display an icon or an image in a Tkinter application.
Patterns #
The PhotoImage class can read GIF and PGM/PPM images from files:
The PhotoImage can also read base64-encoded GIF files from strings. You can use this to embed images in Python source code (use functions in the base64 module to convert binary data to base64-encoded strings):
If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:
You can use a PhotoImage instance everywhere Tkinter accepts an image object. An example:
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.
To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:
Использование объекта PhotoImage() для загрузки и отображения изображений в Tkinter
Объект PhotoImage в Tkinter является основным инструментом для работы с изображениями в форматах GIF, PGM и PPM. Этот метод позволяет создавать, загружать и манипулировать изображениями в приложениях Tkinter.
Создание объекта PhotoImage()
Отображение изображений в различных виджетах
Работа с поддерживаемыми форматами
- GIF: Обычные и анимированные
- PGM: Формат серого изображения
- PPM: Формат пиксельного изображения
Манипуляции с изображениями
Для изменения размера изображения, можно использовать стороннюю библиотеку, такую как Pillow.
Метод subsample() может быть использован для уменьшения размера изображения.
Метод zoom() может быть использован для увеличения размера изображения.
Важные замечания
Если объект PhotoImage сборщиком мусора Python будет считаться неиспользуемым, изображение может исчезнуть. Чтобы избежать этого, нужно сохранить ссылку на изображение.
Анимированные GIF не будут анимироваться в Tkinter автоматически.
Манипуляции с Пикселями
Методы put() и get() позволяют манипулировать отдельными пикселями изображения.
Использование PhotoImage в Canvas
Изображения можно также отображать в холсте Canvas, что предоставляет больше гибкости в расположении и анимации.
Создание пустых изображений
PhotoImage может быть использован для создания пустого изображения определенного размера, которое дальше можно заполнить нужными пикселями.
Заключение
Объект PhotoImage() в Tkinter предоставляет обширный набор инструментов для работы с изображениями. Он не ограничивается только загрузкой и отображением изображений, но также позволяет выполнять манипуляции на уровне пикселей, взаимодействовать с холстом Canvas, интегрироваться с буфером обмена и даже создавать пустые изображения. Эта гибкость делает PhotoImage() мощным выбором для разработчиков, работающих над графическими интерфейсами в Tkinter.
How to add an image in Tkinter?
![]()
There is no «Syntax Error» in the code above — it either ocurred in some other line (the above is not all of your code, as there are no imports, neither the declaration of your path variable) or you got some other error type.
The example above worked fine for me, testing on the interactive interpreter.
Here is an example for Python 3 that you can edit for Python 2 😉

![]()
Following code works on my machine
- you probably have something missing in your code.
- please also check the code files’s encoding.
make sure you have PIL package installed
Your actual code may return an error based on the format of the file path points to. That being said, some image formats such as .gif, .pgm (and .png if tk.TkVersion >= 8.6) is already supported by the PhotoImage class.
Below is an example displaying:

or if tk.TkVersion < 8.6 :
![]()
It’s not a standard lib of python 2.7. So in order for these to work properly and if you’re using Python 2.7 you should download the PIL library first:
How to place an image into a frame in Tkinter?
Import the required libraries and create an instance of tkinter frame. To open an image and place it inside the frame, we will use the Pillow (PIL) library.
Set the size of the frame using geometry method.
Create a frame and specify its height and width. Place the frame at the center of the window using place() method with anchor=’center’.
Open an image using ImageTk.PhotoImage(Image.open(«image»))
Next, create a label object inside the frame and pass the image inside the label.