Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust Image on button

How can I adjust an image to a button in Tkinter?

Actually i have this :

originalImg = Image.open(currentphotofolderPath + file)
img = ImageTk.PhotoImage(originalImg)
Button(photoFrame, image = img, borderwidth=0, height = 200, width = 200)

The problem the image does not adjust to the button with 200x200

I don't want to resize the image with PhotoImage.resize()

like image 456
Kevin Jordil Avatar asked Oct 20 '25 22:10

Kevin Jordil


2 Answers

The zoom() function should fix your issue:

Return a new PhotoImage with the same image as this widget but zoom it with X and Y.

Adding the code line below before instantiating the Button() widget should be helpful:

originalImg = Image.open(currentphotofolderPath + file)
originalImg.zoom(200, 200)
img = ImageTk.PhotoImage(originalImg)    
Button(photoFrame, image=img, borderwidth=0, height=200, width=200)
like image 165
Billal Begueradj Avatar answered Oct 22 '25 16:10

Billal Begueradj


you have a couple of choices, the zoom function as posted by Billal, or you create a resize function:

def Resize_Image(image, maxsize):
    r1 = image.size[0]/maxsize[0] # width ratio
    r2 = image.size[1]/maxsize[1] # height ratio
    ratio = max(r1, r2)
    newsize = (int(image.size[0]/ratio), int(image.size[1]/ratio))
    image = image.resize(newsize, Image.ANTIALIAS)
    return image

which will then resize the Image (not the PhotoImage) to the biggest possible size while retaining the aspect ratio (without knowing it beforehand)

note that the resize method should use less memory than the zoom method (if thats an important factor)

like image 42
James Kent Avatar answered Oct 22 '25 16:10

James Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!