【问题标题】:How to resize the button content with the button如何使用按钮调整按钮内容的大小
【发布时间】:2019-07-27 21:01:12
【问题描述】:

我有一个程序可以在您调整窗口大小时调整按钮大小,但图像不会随按钮调整大小。

这是我的代码:

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

我希望输出如下所示:

但它实际上做的是:

------------编辑---------- -
这需要使用超过 2 个按钮。

【问题讨论】:

标签: python image button tkinter


【解决方案1】:

有趣的问题。 PhotoImage 没有调整大小的方法,但您可以使用 PIL 图像来获得它。如果你没有 PIL,你需要 pip install pillow 来获得它。

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

请注意,您必须定义窗口的初始大小才能使其正常工作。如果你不这样做,那么每次调整大小都会触发它进一步增长。

【讨论】:

  • 当我使用 2 个按钮时,第一个按钮只会在第二个按钮上展开。
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
相关资源
最近更新 更多