Как вставить картинку в ткинтер
Как добавить изображение в Tkinter?
Как добавить изображение в Tkinter?
Это дало мне синтаксическую ошибку:
9 ответов
Есть ли какой-нибудь способ добавить пользовательское изображение к tkinter, встроенному в tkMessageBox?
Python 3.3.1 [MSC v.1600 32 бит (Intel)] на win32 14.May.2013
Это сработало для меня, следуя приведенному выше коду
Приведенный выше пример отлично сработал для меня, тестируя на интерактивном интерпретаторе.
Вот пример для Python 3, который вы можете отредактировать для Python 2 😉
Следующий код работает на моей машине
убедитесь, что у вас установлен пакет PIL
Это не стандартная библиотека python 2.7. Поэтому, чтобы они работали должным образом, и если вы используете Python 2.7, вы должны сначала загрузить библиотеку PIL: Прямая ссылка для загрузки: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe После ее установки выполните следующие действия:
Отредактируйте свой script.py
Надеюсь, это поможет!
Как добавить изображение в виджет в tkinter? Почему когда я использую этот код он не работает: some_widget.config(image=PhotoImage(file=test.png), compound=RIGHT) но это работает?: an_image=PhotoImage(file=test.png) some_widget.config(image=anImage, compound=RIGHT)
Ниже приведен пример отображения:
или если tk.TkVersion :
Это проблема с версией Python. Если вы используете последнюю версию, то ваш старый синтаксис не будет работать и выдаст вам эту ошибку. Пожалуйста, следуйте коду @Josav09’s, и все будет в порядке.
Просто преобразуйте изображение в формате jpg в формат png. Это будет работать 100%.
Похожие вопросы:
Используя tkinter, я пытаюсь отобразить изображение внутри границы виджета ввода. Я попытался поискать в Google, но безуспешно, у кого-то есть идея, как это сделать?
У меня есть относительно простой скрипт python, использующий tkinter GUI код выглядит примерно так from Tkinter import * master = Tk() def f1(): print function f1 does stuff, nice.. title =.
Есть ли какой-нибудь способ добавить пользовательское изображение к tkinter, встроенному в tkMessageBox?
Как добавить изображение в виджет в tkinter? Почему когда я использую этот код он не работает: some_widget.config(image=PhotoImage(file=test.png), compound=RIGHT) но это работает.
Я использую python 3 и tkinter. Я хочу поместить свое собственное изображение в качестве значка в корневое окно вместо значка по умолчанию tkinter. Пожалуйста, помогите мне. Я пробовал этот код, но.
Я создал простую программу открытия изображений, которая открывает изображение, выбранное из filedialog, нажав кнопку, но везде, где я выбираю другое изображение, оно просто появляется под текущим.
Я пытаюсь создать приложение погоды в Tkinter GUI. Он прекрасно работает. Я хочу добавить к нему фоновое изображение, но оно не появляется. сначала я сделал это без опорной линии, но это не.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.
Python | Добавить изображение на кнопку Tkinter
Tkinter — это модуль Python, который используется для создания приложений с графическим интерфейсом пользователя с помощью разнообразных виджетов и функций. Как и любой другой модуль GUI, он также поддерживает изображения, т.е. вы можете использовать изображения в приложении, чтобы сделать его более привлекательным.
Важное замечание: Если на кнопке указаны как изображение, так и текст, текст будет преобладать, и на кнопке будет отображаться только изображение. Но если вы хотите показать как изображение, так и текст, вы должны передать составные в настройках кнопки.
Button(master, text = «Button», image = «image.png», compound=LEFT)
Синтаксис:
любой допустимый путь, доступный на вашем локальном компьютере.
Код № 1:
# импорт только этих функций
# которые нужны
from tkinter import *
from tkinter.ttk import *
# создание окна tkinter
# Добавление виджетов в корневое окно
# Создание объекта фотоизображения для использования изображения
photo = PhotoImage( file = r «C:\Gfg\circle.png» )
# здесь, опция изображения используется для
# установить изображение на кнопку
Выход:
При выводе обратите внимание, что на кнопке отображается только изображение, а размер кнопки также больше обычного размера, потому что мы не установили размер изображения.
# импорт только этих функций
# которые нужны
from tkinter import *
from tkinter.ttk import *
# создание окна tkinter
# Добавление виджетов в корневое окно
# Создание объекта фотоизображения для использования изображения
photo = PhotoImage( file = r «C:\Gfg\circle.png» )
# Изменение размера изображения для размещения на кнопке
# здесь, опция изображения используется для
# установить изображение на кнопку
# составная опция используется для выравнивания
# изображение на левой стороне кнопки
compound = LEFT).pack(side = TOP)
Выход:
Обратите внимание, что как текст, так и изображение появляются, а размер изображения также невелик.
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
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
make sure you have PIL package installed
Below is an example displaying:
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:
Edit your script.py
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
Related
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.12.16.41042
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Загрузка изображений в Tkinter с использованием PIL
В этой статье мы научимся загружать изображения из пользовательской системы в окно Tkinter с помощью модуля PIL. Эта программа откроет диалоговое окно, чтобы выбрать нужный файл из любого каталога и отобразить его в окне tkinter.
Установите требования —
Используйте эту команду для установки Tkinter:
Используйте эту команду для установки PIL:
Импорт модулей —
from tkinter import *
# загрузка библиотеки изображений Python
from PIL import ImageTk, Image
# Чтобы диалоговое окно открывалось при необходимости
from tkinter import filedialog
Примечание. Модуль ImageTk поддерживает создание и изменение объектов Tkinter BitmapImage и PhotoImage из изображений PIL, а filedialog используется для filedialog диалогового окна, когда вы открываете файл из любой точки вашей системы или сохраняете файл в определенной позиции или месте.
Функция для создания окна Tkinder, состоящего из кнопки —
# Установить заголовок в качестве загрузчика изображений
root.title( «Image Loader» )
# Установите разрешение окна
root.geometry( «550×300 + 300 + 150» )
# Разрешить изменение размера окна
# Создайте кнопку и поместите ее в окно, используя сетку
Функция для размещения изображения на окне —
# Выберите Imagename из папки
# изменить размер изображения и применить высококачественный фильтр сглаживания
# Класс PhotoImage используется для добавления изображения в виджеты, иконки и т. Д.
panel = Label(root, image = img)
# установить изображение как img
Функция openfilename вернет имя файла изображения.
Функция для возврата имени файла, выбранного из диалогового окна —
# открыть файл диалоговое окно для выбора изображения
# Диалоговое окно имеет заголовок «Открыть»
filename = filedialog.askopenfilename(title = ‘»pen’ )