Stemboy4002
Stemboy4002

Reputation: 67

How to resize the button content with the button

I have a program that resizes the buttons when you resize the window but the image doesn't resize with the buttons.

This is my code:

l = Label(window, image=img).grid(row=0, column=0, rowspan=3, sticky='nesw')

con = Frame(window).grid(row=0, column=1, sticky='nesw')

nextImg    = PhotoImage(file='nextImg.png')
lastImg    = PhotoImage(file='lastImg.png')
ok = PhotoImage(file="ok".png')

nextCam = Button(con, image=nextImg,    command=nxt, background='#2B2B2B').grid(row=0, column=1, sticky='nesw')
lastCam = Button(con, image=lastImg,    command=lst, background='#2B2B2B').grid(row=2, column=1, sticky='nesw')
takeImg = Button(con, image=ok, command=ok, background='#2B2B2B').grid(row=1, column=1, sticky='nesw')

I expect the output to look like this: What I expect

But what it actually does is:enter image description here

------------------------Edit-----------------------
This needs to work with more than 2 buttons.

Upvotes: 0

Views: 106

Answers (1)

Novel
Novel

Reputation: 13729

Interesting question. PhotoImage does not have a resize method, but you could use a PIL image to get that. If you don't have PIL you need to pip install pillow to get it.

import tkinter as tk
from PIL import Image, ImageTk

class ImageButton(tk.Button):
    """A button that displays an Image and resizes the image as the Button size changes"""
    def __init__(self, master=None, image=None, **kwargs):
        super().__init__(master, **kwargs)
        if not image: return # no image provided; act as a normal Button
        if isinstance(image, str):
            self.image = Image.open(image)
        elif isinstance(image, Image.Image):
            self.image = image
        else:
            raise TypeError("'image' argument must be a PIL.Image or filename")
        self.bind("<Configure>", self._on_configure)
    def _on_configure(self, event=None):
        size = event.width-4, event.height-4
        self.photoimage = ImageTk.PhotoImage(self.image.resize(size))
        self.config(image=self.photoimage)

### test / demo code: ###

def main():
    root = tk.Tk()
    root.geometry('200x200')
    win = ImageButton(root, image="ON.gif")
    win.pack(fill=tk.BOTH, expand=True)
    root.mainloop()

if __name__ == '__main__':
    main()

Note that you MUST define the initial size of the window for this to work. If you don't then every resize will trigger it to grow some more.

Upvotes: 1

Related Questions