How to have image and text in one button in Tkinter?

PythonTkinterServer Side ProgrammingProgramming

We can load the images in a Tkinter application using the PhotoImage(image location) function, which takes the image location as the parameter and displays the image on the window object. However, when we try to add an image to the button, it generally appears on the button while hiding the button text. Therefore, to make the button text and pictures relative to each other, we typically use the compound property. It takes one of four positional arguments – LEFT, RIGHT, TOP, and BOTTOM, each defining the image’s position on the button.


In this example, we have used this image to make it relative to the button.

#Import tkinter library
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of Tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
#Define a function to close the window
def close_win():
#Load the image
image ='preview.png')
#Resize the Image
image = image.resize((50,50), Image.ANTIALIAS)
#Convert the image to PhotoImage
img= ImageTk.PhotoImage(image)
#Create a Label
Label(win, text="Click the below button to close the window",font=('Aerial 15 bold')).pack(pady=20)
#Create a label with the image
button= Button(win, text="Click Me",font= ('Helvetica 15 bold'),image=img, compound= LEFT, command=close_win)


The above code will display a window containing a button with an image and a text label. When we click the button, it will close the window.

Published on 22-Apr-2021 07:08:16