'limit the size of a button with an image

Problem:

I want to create my own widget that uses an image in a button, but the image causes the button to be way too big. How can I resize the button to the normal button size (the size of normal Text).

Code:

add = Button(master=controlfrm , image=myimagepath)
add.pack()

Result:

this is the result of my code

Goal:

I want the image to be resized to a height equal to the Entry widget.



Solution 1:[1]

Tkinter doesn't shrink or expand images. The best you can hope for is to use the zoom and subsample methods on a PhotoImage, which will allow you to change the size by a factor of 2.

If you want to use an image on a button, and you want it to be smaller, the best solution is to start with an image that is the right size.

Solution 2:[2]

You can use ImageTk.PhotoImage to resize the image and call it in a Button. Use the zoom to shrink or expand your button image.

button_image_file = "images/square-button-1.png"
button_image      = Image.open(button_image_file)
zoom = .40  # multiplier for image size by zooming -/+
pixels_x, pixels_y = tuple([int(zoom * x) for x in button_image.size])
button_image = ImageTk.PhotoImage(button_image.resize((pixels_x, pixels_y)))

button = tk.Button(root_main, text="Button", command=lambda: do_something(), font="Arial",
                    bg="#20bebe", fg="white",  image=button_image)
button.place(rely=0.01, relx=.01)

Solution 3:[3]

Try to set the width and height properties of the image, so that the image can fit to size of the button that you require.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bryan Oakley
Solution 2 Irshad
Solution 3 Asma Ali