Lesson-11: Adding Tkinter Button Picture

Tkinter Button Picture

Add a picture to the Tkinter button. In this course, we will visually enrich a button that we add to our window with the tkinter module. A button that we will add to the window will be decorated with a picture. During this process, we will use the PIL library. Check out the codes below.

Adding Picture To The Tkinter Button

import tkinter as tk
from PIL.ImageTk import PhotoImage

pencere = tk.Tk()
pencere.title("Adding Image to Button")
pencere.geometry("500x500+50+100")
pencere.resizable(width="FALSE", height="FALSE")



tk.mainloop()

First, we need to set up the PIL library. When installing a library in Python, we need to install the pip package installation manager on the system. How to install pip now? and how to set up the PIL library? Let’s find answers to these questions.

How To Install Pip?

Before we begin, we have an important point to make. With Python version 3.4, pip package manager is already installed. If your python version is older, just write the following code in the terminal section of pycharm or other python editors.

#Windows için...
python -m pip install -U pip

#Mac için...
sudo easy_install pip


#Linux için...
sudo apt-get install python-pip

PIL Library

Python Image Library. With this library, we can easily add images in python. In order to use the PIL library, we must first install it. We can install pip package manager by typing the following codes into the terminal.

pip install Pillow

Now let’s move on to adding images to the button with the tkinter module.

import tkinter as tk
from PIL.ImageTk import PhotoImage



pencere = tk.Tk()
pencere.title("Adding Image to Button")
pencere.geometry("500x500+50+100")
pencere.resizable(width="FALSE", height="FALSE")

simge1 = PhotoImage(file="kitap1.png")

düğme1=tk.Button(text="KİTAP LİSTESİ", image=simge1,compound="top",font="Times 12 bold",bg="purple",fg="white")

düğme1.place(relx=0.2,rely=0.1,width=120,height=140)

tk.mainloop()

After importing the necessary libraries to our project, we make window adjustments. Our window is 500×500 in size and adjustable features will be displayed off. Immediately after that, we define the file” kitap1.png” to the icon1 variable with the following code.

simge1 = PhotoImage(file="kitap1.png")

Here we should note that the file” kitap1.png” should be in the same folder as the python file. If it’s not in the same folder, we need to specify its path.

Later;

düğme1=tk.Button(text="KİTAP LİSTESİ", image=simge1,compound="top",font="Times 12 bold",bg="purple",fg="white")

we need to give the value “image=simge1” with the code.

Screen Shot

Tkinter Button Picture

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *