Tkinter как вывести картинку

Как вывести изображение из файла в окне?

Помощь в написании контрольных, курсовых и дипломных работ здесь.

После выбора файла в диалоговом окне, разместить изображение из файла в canvas
Кликаю по кнопке открыть выбираю картинку, нажимаю открыть и у меня всё:D, подскажите, как после.

Вывести изображение в окне
Создаю 2ое окно поверх 1-ого(new_window_1) и в нём необходимо вывести изображение.Если не.

Как вывести изображение из файла
Выполняю задачу по Django, и мне нужно, чтобы изображение, созданное с помощью библиотеки.

Нажать на изображение и вывести сайт в новом окне в iframe
Всем привет! Ребят, задолбался я перебирать туеву хучу вариантов.. Сам я почти новичок, так вот как.

выводи в метке Label (свойство image)

Добавлено через 22 минуты
примерный кусок кода (для картинки в gif-формате):

Как в консоли вывести изображение из файла?
Image.Picture.LoadFromFile( ); Наподобие такого только на Паскаль.

Как вывести в webBrowser изображение из файла ресурсов?
Помогите пожалуйста советом, мучаюсь уже несколько дней. Надо извлечь изображение из файлов.

Как сохранить изображение из формы в файл и вывести из файла на страничку?
Здравствуйте Вопрос в том: как с помощью php сохранить изображение из формы в файл? как.

Как вывести на форму изображение, имя файла которого вводится в Text1
Реализовать интерфейс с объектами, представленными на рисунке. При нажатии на кнопку CommandButton1.

Почему изображение в окне Scene и в окне Game сильно отличается?
Почему изображение в окне Scene и в окне Game сильно отличается?

Источник

Python Tkinter Image + Examples

In this Python tutorial, we will learn how to add image in Python Tkinter. let us start the Python Tkinter Image with below examples.

  • Python Tkinter Image
  • Python Tkinter Image Display
  • Python Tkinter Image Button
  • Python Tkinter Image Background
  • Python Tkinter Image Resize
  • Python Tkinter Image Size
  • Python Tkinter Image Label
  • Python Tkinter Image Doesn’t Exist

Python Tkinter Image

Python Tkinter has the method PhotoImage which allows reading images in Python Tkinter. And then Image can be placed by providing adding PhotoImage variable in image property of widgets like Label, Button, Frame, etc.

  • There are three ways of adding images on Python Tkinter.
    • PhotoImage
    • PillowModule
  • PhotoImage is the built-in library that comes with Python Tkinter and provides limited options. But is good to get started or for small tasks wherein the application just aims at putting the image on the screen. Also, it supports limited image extensions.
  • Pillow module in Python Tkinter provides more features like you can read images of any extension, resize the image, etc. The Pillow module needs to be installed before use.
  • Pillow can be installed using pip or pip3 in Python Tkinter.
  • In our below example, we have demonstrated the use of PhotoImage. Pillow is discussed in the later sections of the same tutorial. We will be demonstrating the best method to be used in the situation.

Code

This is the basic code to demonstrate how to add images in Python Tkinter. Since the below code is just to display an image so we have used the PhotoImage method in Python Tkinter.

Output

In this output, image is displayed using label widget and since we have not provided any geometry so the application size is to the size of image.

Python Tkinter Image Display

Image in Python Tkinter can be displayed either by using the PhotoImage module or by using the Pillow library.

  • In this section, we will display images using both PhotoImage and Pillow libraries. Also, we will use the create_image method from the canvas.
  • Canvas is used to add images or text on the application screen.

Code using PhotoImage method

In this code, you can observe that we have not imported any libraries as PhotoImage automatically loaded when everything is imported.

Output of PhotoImage method

The image is displayed on the canvas and it is showing incomplete because we have provided height and width of canvas less than the size of image.

Code using Pillow Library

In this code, we have imported ImageTk, the Image method from the PIL library. PIL is the short name for a pillow. Though the code looks much similar to the previous one now we can read more image extensions like jpg, png, bitmap, etc.

Output Of image displayed using Pillow Library

The output is similar to the PhotoImage section, and photo is incomplete because the size of the window provided is less than the original size of image.

Python Tkinter Image Button

Button widget in Python Tkinter has image property, by providing image variable we can place image on the button widget.

  • The first step in the process is to read the image and to do so we will use the PhotoImage method in Python Tkinter.
  • Button in Tkinter has image property, you can provide the variable assigned to PhotoImage here.
  • In this way an image can be placed on the button widget in Python Tkinter.

In this section, we will learn how to put image on the button in Python Tkinter.

Code

In this code, we have added an image on the button. User can click on the image to perform the action.

Output

In this output, Download image is added on the button. Users can click on this image to download the file.

Python Tkinter Image Background

In this section, we will learn how to insert a background image in Python Tkinter. In other words, how to set background image in Python Tkinter.

  • There are mainly two ways of placing background in Python Tkinter
    • Using Place layout manager we can put the background image on the label and the stretch it all the way to the screen.
    • Using canvas create_image method we can put the image on the screen and later using create_text method of canvas we can place text widget.
  • Out of these two methods, second method which says using canvas is more efficient and accurate and we will recommend to do using canvas.
  • In the below example, we have created an application using canvas. The application has background image, text and a button. When user will click on the button, he/she will be redirected to our website.

Code

In this code, we have imported webbrowser so that we can open the webpage. We have placed image in the background using canvas method create_image and then using create _text and create_window we have placed the button and text on the window.

Output

In this output, you can see that application has background image, text and button. When user will click on the button he/she will be redirected to a website.

Python Tkinter Image Resize

In this section, we will learn how to resize the image in Python Tkinter.

  • Using Pillow library in Python Tkinter we can resize the images. to import Pillow use this code from PIL import Image, ImageTk
  • image.resize((w, h)) this command allows us to change the height(h) and width(w) of the image.
  • In the below example, we have created an application in which the user can provide width and height and the image will change the size in real-time.

Code

In this code, we have used Image method from Pillow module to change the size of the image.

Output

In this output, you can see that image is resizing as per the height and width provided by the user. The is a full fledged application created in Python Tkinter that can be used for daily activities.

Python Tkinter Image Size

In this section, we will learn how to get the image size in Python Tkinter.

  • first thing in the process is to import Image, ImageTk from PIL.
  • then ImageTk provides width and height method using which we can get the size of an image.

Code

In this code, text=f’width: height: this command displays the height and width of the image. Here, img is the variable that stores the file file.

Output

In this output, you can see that height and width of the image is displayed at the bottom of the page.

Python Tkinter Image Label

In this section, we will learn how to set image on the Label widget in Python Tkinter.

  • The label widget in Python Tkinter is used to display text and images on the application window.
  • The label widget has a property image. Adding an image file to this property will set the image on the label widget.
  • If you are dealing with PNG images then you can simply use the PhotoImage method which is a built-in method in Python Tkinter.
  • For advanced features and all extensions, use the Image, ImageTk in pillow library.

Code

Here is the simple code to display image using Label widget in Python Tkinter.

Output

Python Tkinter Image Doesn’t Exist

This is a common error that is encountered by almost all the programmers working with images in Python Tkinter that says, Python Tkinter Image Doesn’t Exist.

  • There are mainly three reasons for this error:
    • image path provided is incorrect
    • You have read the image using var = Image.open(pathToImage) but you have not passed it to ImageTk.PhotoImage(var) .
    • declare a global variable in case you are trying image in function.
  • _tkinter.TclError: couldn’t recognize data in image file “images/workstation.jpg”
  • If you are seeing the above error code, that means you are trying to use a JPG image file using PhotoImage.
  • To fix that either use a PNG image file or switch to Pillow. As Pillow module allows the use of various image extensions.

You may like the following Python tkinter tutorials:

In this tutorial, we have learned how to add images in Python Tkinter. Also, we have covered these topics.

  • Python Tkinter Image
  • Python Tkinter Image Display
  • Python Tkinter Image Button
  • Python Tkinter Image Background
  • Python Tkinter Image Resize
  • Python Tkinter Image Size
  • Python Tkinter Image Label
  • Python Tkinter Image Doesn’t Exist

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

Источник

Библиотека Tkinter: Изображения.

Для работы с изображениями в Tkinter имеется два класса BitmapImage и PhotoImage.

BitmapImage представляет собой простое двухцветное изображение, PhotoImage – полноцветное изображение.

BitmapImage

Конструктор класса принимает следующие аргументы:

  • background и foreground – цвета фона и переднего плана для изображения. Поскольку изображение двухцветное, то эти параметры определяют соответственно чёрный и белый цвет;
  • file и maskfile – пути к файлу с изображением и к маске (изображению, указывающему какие пиксели будут прозрачными);
  • data и maskdata – вместо пути к файлу можно указать уже загруженные в память данные изображения. Данная возможность удобна для встраивания изображения в программу.

PhotoImage

PhotoImage позволяет использовать полноцветное изображение. Кроме того у этого класса есть несколько (достаточно примитивных) методов для работы с изображениями. PhotoImage гарантированно понимает формат GIF. Аргументы конструктора:

  • file – путь к файлу с изображением;
  • data – вместо пути к файлу можно указать уже загруженные в память данные изображения. Изображения в формате GIF могут быть закодированы с использованием base64. Данная возможность удобна для встраивания изображения в программу;
  • format – явное указание формата изображения;
  • width, height – ширина и высота изображения;
  • gamma – коррекция гаммы;
  • palette – палитра изображения.

Будет выведено изображение в главную форму:

Источник

How to add an image in Tkinter?

How do I add an image in Tkinter?

This gave me a syntax error:

9 Answers 9

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

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

  1. you probably have something missing in your code.
  2. 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 :

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: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:

    Make sure that your script.py is at the same folder with the image you want to show.

Edit your script.py

Hope that helps!

This code works for me, also you should consider if you have any other button or labels in that window and you not use .place() it will not work properly.

It’s a Python version problem. If you are using the latest, then your old syntax won’t work and give you this error. Please follow @Josav09’s code and you will be fine.

Just convert the jpg format image into png format. It will work 100%.

Not the answer you’re looking for? Browse other questions tagged python user-interface tkinter or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.3.40639

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Читайте также:  Знаки как можно стирать вещи
Оцените статью