Python tkinter загрузка изображения

Tkinter PhotoImage – Displaying Images with Tkinter

Tkinter is a very well rounded GUI library with support for various GUI elements. One of the many features that Tkinter supports is the displaying of images within it’s GUI. This is accomplished using the Tkinter PhotoImage Class, which takes an image’s filepath and creates an object from it that can be used with the other GUI elements.

Using Tkinter PhotoImage

The process is quite simple. All you have to do is pass the file path of the Image you want to import, into the PhotoImage class. This creates an image object which Tkinter understands, allowing it to be used with other GUI elements like the Canvas or Labels.

Here is our PhotoImage example code:

from tkinter import * root = Tk() image = PhotoImage(file="Python.png")

We now have our image object stored in the variable image . In the section we’ll explain how to actually display this image now.

If the image you want to display is not in the same folder/directory, then you’ll have to specify the entire filepath, not just the name of the file.

Displaying the Image

As mentioned earlier, we need a suitable GUI element to actually display the image. Surprisingly, most GUI elements do support it in one way or the other. Let’s quickly go through them.

Читайте также:  Welcome To My Domain

Tkinter Label (Image)

from tkinter import * root = Tk() image = PhotoImage(file="python.png") label = Label(root, image = image) label.pack() root.mainloop()

Several GUI elements, such as labels and buttons have the image parameter to which you can assign a suitable image object, just as we have down in the above code.

The output is as shown below.

Label Image Display - Tkinter PhotoImage

Keep in mind that Tkinter itself does not have the ability to control (resize) the images it displays. The image displayed above was displayed in it’s original dimensions (size).

Displaying Images on a Canvas

The Tkinter canvas is designed to support features like drawing shapes, images and even displaying images. Hence it has a little more control over the images than the Tkinter Label does.

from tkinter import * root = Tk() image = PhotoImage(file="python.png") canvas = Canvas(width = 300, height = 300, bg='black') canvas.create_image(200, 200, image = image) canvas.pack() root.mainloop()

The first two parameters in the create_image() function represent the width and height of the image respectively. However, as you can see in the image below, that image appears to be cropped. This is because the dimensions we gave the image were too small.

Canvas Image display

Displaying Images on Buttons

Even though is a tutorial on the Tkinter PhotoImage class, I want to show you some other options as well. In the below code we use a combination of PhotoImage + Pillow (python image library) to display the image in the required format.

We open the Image using Pillow’s open() function, followed by the resize function, which takes a tuple containing the new width and height. Then we converted this image to a Tkinter compatible format using ImageTk.PhotoImage() .

from tkinter import * from PIL import Image, ImageTk root = Tk() root.geometry('200x200') image = Image.open("python.png") image = image.resize((20, 20)) image = ImageTk.PhotoImage(image) button = Button(width = 100, height = 20, image = image) button.pack(padx = 20, pady = 50) root.mainloop()

We add the final image to the button the same way we did with the labels, and we get the following output. Personally, I think it looks pretty good. Resizing it was nessacery, otherwise the image would have inflated the size of the button.

Tkinter PhotoImage

This marks the end of the Tkinter PhotoImage tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Источник

Python. Работа с изображениями в tkinter.

На уроке Python. Работа с изображениями мы с вами научились загружать и отображать картинки, а также всяко извращаться с ними. Это мы делали при помощи библиотеки PIL. На уроке Python. GUI мы с вами при помощи библиотеки tkinter создавали виндовый интерфейс программы: всякие кнопочки, флажки, и прочие элементы управления. Но возникает вопрос: а нельзя ли при помощи tkinter как-то выводить изображение на виндовую форму? Можно. Например вот такая программа:

import tkinter from PIL import Image, ImageTk root = tkinter.Tk() # создаем рабочую область frame = tkinter.Frame(root) frame.grid() #Добавим метку label = tkinter.Label(frame, text="Hello, World!").grid(row=1,column=1) # вставляем кнопку but = tkinter.Button(frame, text="Кнопка").grid(row=1, column=2) #Добавим изображение canvas = tkinter.Canvas(root, height=400, width=700) image = Image.open("d:/3/Dscn0116.jpg") photo = ImageTk.PhotoImage(image) image = canvas.create_image(0, 0, anchor='nw',image=photo) canvas.grid(row=2,column=1) root.mainloop()

Что интересно, PIL здесь нужен, чтобы загружать изображения типа jpg, gif-ы и png можно открыть и без него:

import tkinter root = tkinter.Tk() # создаем рабочую область frame = tkinter.Frame(root) frame.grid() #Добавим метку label = tkinter.Label(frame, text="Hello, World!").grid(row=1,column=1) # вставляем кнопку but = tkinter.Button(frame, text="Кнопка").grid(row=1, column=2) #Добавим изображение canvas = tkinter.Canvas(root, height=400, width=700) img = tkinter.PhotoImage(file = 'd:/3/Dscn0116.png') image = canvas.create_image(0, 0, anchor='nw',image=img) canvas.grid(row=2,column=1) root.mainloop()

А теперь попробуем при нажатии на кнопку сменить изображение:

import tkinter from PIL import Image, ImageTk root = tkinter.Tk() # создаем рабочую область frame = tkinter.Frame(root) frame.grid() # Добавим метку label = tkinter.Label(frame, text="Hello, World!").grid(row=1, column=1) image = Image.open("d://1//DSCN1128.png") photo = ImageTk.PhotoImage(image) def my_event_handler(): print("my_event_handler") image = Image.open("d://1//original.jpg") photo = ImageTk.PhotoImage(image) image = canvas.create_image(0, 0, anchor='nw', image=photo) canvas.grid(row=2, column=1) # вставляем кнопку but = tkinter.Button(frame, text="Кнопка", command=my_event_handler).grid(row=1, column=2) # Добавим изображение canvas = tkinter.Canvas(root, height=400, width=700) image = canvas.create_image(0, 0, anchor='nw', image=photo) canvas.grid(row=2, column=1) root.mainloop()

Но не тут то было. При нажатии на кнопку изображение не меняется. Хотя, казалось бы, все написано правильно, и наш обработчик событий работает, наше сообщение, что мы выводим командой print выводится в окно сообщений. В чем же дело? А дело в сборщике мусора (garbage collector). Как только мы вышли из my_event_handler, локальные переменные тут же уничтожаются сборщиком мусора. Именно поэтому мы видим на форме ту же самую картинку, что и до нажатия на кнопку. Как же быть? Не использовать локальные переменные. Давайте объявим класс, пусть изображение и прочие объекты хранятся в его полях:

import tkinter from PIL import Image, ImageTk class App: def __init__(self): self.root = tkinter.Tk() # создаем рабочую область self.frame = tkinter.Frame(self.root) self.frame.grid() # Добавим метку self.label = tkinter.Label(self.frame, text="Hello, World!").grid(row=1, column=1) self.image = Image.open("d://1//DSCN1128.png") self.photo = ImageTk.PhotoImage(self.image) # вставляем кнопку self.but = tkinter.Button(self.frame, text="Кнопка", command=self.my_event_handler).grid(row=1, column=2) # Добавим изображение self.canvas = tkinter.Canvas(self.root, height=600, width=700) self.c_image = self.canvas.create_image(0, 0, anchor='nw', image=self.photo) self.canvas.grid(row=2, column=1) self.root.mainloop() def my_event_handler(self): print("my_event_handler") self.image = Image.open("d://1//original.jpg") self.photo = ImageTk.PhotoImage(self.image) self.c_image = self.canvas.create_image(0, 0, anchor='nw', image=self.photo) self.canvas.grid(row=2, column=1) app= App()

Источник

Python tkinter загрузка изображения

Tkinter Advance

  • Getting screen’s height and width using Tkinter | Python
  • Python | How to dynamically change text of Checkbutton
  • Python | focus_set() and focus_get() method
  • Search String in Text using Python-Tkinter
  • Autocomplete ComboBox in Python-Tkinter
  • Autohiding Scrollbars using Python-tkinter
  • Python Tkinter – Validating Entry Widget
  • Tracing Tkinter variables in Python
  • Python | setting and retrieving values of Tkinter variable
  • Tkinter | Adding style to the input text using ttk.Entry widget
  • Python | after method in Tkinter
  • destroy() method in Tkinter | Python
  • Text detection using Python
  • Python | winfo_ismapped() and winfo_exists() in Tkinter
  • Collapsible Pane in Tkinter | Python
  • Creating a multiple Selection using Tkinter
  • Creating Tabbed Widget With Python-Tkinter
  • Open a new Window with a button in Python-Tkinter
  • Cryptography GUI using python

Applications and Projects

  • Python | Simple GUI calculator using Tkinter
  • Create Table Using Tkinter
  • Python | GUI Calendar using Tkinter
  • File Explorer in Python using Tkinter
  • Python | ToDo GUI Application using Tkinter
  • Python: Weight Conversion GUI using Tkinter
  • Python: Age Calculator using Tkinter
  • Python | Create a GUI Marksheet using Tkinter
  • Python | Loan calculator using Tkinter
  • Python | Create a digital clock using Tkinter
  • Make Notepad using Tkinter
  • Color game using Tkinter in Python
  • Python | Simple FLAMES game using Tkinter
  • Simple registration form using Python Tkinter
  • How to create a COVID19 Data Representation GUI?

Introduction

Widgets

  • Python | Creating a button in tkinter
  • Python | Add style to tkinter button
  • Python | Add image on a Tkinter button
  • Python Tkinter – Label
  • Python Tkinter | Create LabelFrame and add widgets to it
  • RadioButton in Tkinter | Python
  • Python Tkinter – Checkbutton Widget
  • Python Tkinter – Canvas Widget
  • Python Tkinter | Create different shapes using Canvas class
  • Python Tkinter | Create different type of lines using Canvas class
  • Python Tkinter | Moving objects using Canvas.move() method
  • Combobox Widget in tkinter | Python
  • maxsize() method in Tkinter | Python
  • minsize() method in Tkinter | Python
  • resizable() method in Tkinter | Python
  • Python Tkinter – Entry Widget
  • Tkinter – Read only Entry Widget
  • Python Tkinter – Text Widget
  • Python Tkinter – Message
  • Python | Menu widget in Tkinter
  • Python Tkinter – Menubutton Widget
  • Python Tkinter – SpinBox
  • Progressbar widget in Tkinter | Python
  • Python-Tkinter Scrollbar
  • Python Tkinter – ScrolledText Widget
  • Python Tkinter – ListBox Widget
  • Scrollable ListBox in Python-tkinter
  • Python Tkinter – Frame Widget
  • Scrollable Frames in Tkinter
  • How to make a proper double scrollbar frame in Tkinter
  • Python Tkinter – Scale Widget
  • Hierarchical treeview in Python GUI application
  • Python-Tkinter Treeview scrollbar
  • Python Tkinter – Toplevel Widget
  • Python | askopenfile() function in Tkinter
  • Python | asksaveasfile() function in Tkinter
  • Python – Tkinter askquestion Dialog
  • Python Tkinter – MessageBox Widget
  • Create a Yes/No Message Box in Python using tkinter
  • Change the size of MessageBox – Tkinter
  • Different messages in Tkinter | Python
  • Change Icon for Tkinter MessageBox
  • Python – Tkinter Choose color Dialog
  • Popup Menu in Tkinter

Geometry Management

Binding Functions

Tkinter Advance

  • Getting screen’s height and width using Tkinter | Python
  • Python | How to dynamically change text of Checkbutton
  • Python | focus_set() and focus_get() method
  • Search String in Text using Python-Tkinter
  • Autocomplete ComboBox in Python-Tkinter
  • Autohiding Scrollbars using Python-tkinter
  • Python Tkinter – Validating Entry Widget
  • Tracing Tkinter variables in Python
  • Python | setting and retrieving values of Tkinter variable
  • Tkinter | Adding style to the input text using ttk.Entry widget
  • Python | after method in Tkinter
  • destroy() method in Tkinter | Python
  • Text detection using Python
  • Python | winfo_ismapped() and winfo_exists() in Tkinter
  • Collapsible Pane in Tkinter | Python
  • Creating a multiple Selection using Tkinter
  • Creating Tabbed Widget With Python-Tkinter
  • Open a new Window with a button in Python-Tkinter
  • Cryptography GUI using python

Applications and Projects

  • Python | Simple GUI calculator using Tkinter
  • Create Table Using Tkinter
  • Python | GUI Calendar using Tkinter
  • File Explorer in Python using Tkinter
  • Python | ToDo GUI Application using Tkinter
  • Python: Weight Conversion GUI using Tkinter
  • Python: Age Calculator using Tkinter
  • Python | Create a GUI Marksheet using Tkinter
  • Python | Loan calculator using Tkinter
  • Python | Create a digital clock using Tkinter
  • Make Notepad using Tkinter
  • Color game using Tkinter in Python
  • Python | Simple FLAMES game using Tkinter
  • Simple registration form using Python Tkinter
  • How to create a COVID19 Data Representation GUI?

Источник

Оцените статью