Kevin Jordil
Kevin Jordil

Reputation: 183

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()

Upvotes: 4

Views: 13422

Answers (2)

Andath
Andath

Reputation: 22714

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)

Upvotes: 2

James Kent
James Kent

Reputation: 5933

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)

Upvotes: 1

Related Questions