【问题标题】:Cannot resize list of images on canvas无法调整画布上图像列表的大小
【发布时间】:2019-12-14 23:30:28
【问题描述】:

我的画布上有一个矩形和两个图像。当我通过向下和向右拖动窗口角来调整大小时,会发生这种情况:

  • 蓝色矩形正确调整大小。
  • 红色和绿色图像仅适当调整了边框大小。
  • 无论我如何尝试使用 ImageTk.PhotoImage() 重新生成红色和绿色图像,它们的大小都保持不变。

这是我的python代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

from PIL import Image, ImageTk

root = Tk()

images = []     # to hold the newly created image
fills = []      # associated list of fill attributes

# a subclass of Canvas for dealing with resizing of windows
class ResizingCanvas(Canvas):
    def __init__(self,parent,**kwargs):
        Canvas.__init__(self,parent,**kwargs)

        self.bind("<Configure>", self.on_resize)
        self.height = self.winfo_reqheight()
        self.width = self.winfo_reqwidth()

    def on_resize(self,event):
        # determine the ratio of old width/height to new width/height
        wscale = float(event.width)/self.width
        hscale = float(event.height)/self.height
        # Save new values as old values
        self.width = event.width
        self.height = event.height
        # resize images
        for idx, image in enumerate(images):
            fill=fills[idx]
            dimensions = "image size: %dx%d" % (image.width(), image.height())
            events = "event size: %dx%d" % (event.width, event.height)
            neww=int(image.width()*wscale)
            newh=int(image.height()*hscale)
            image = Image.new('RGBA', (neww, newh), fill)
            image = ImageTk.PhotoImage(image)
#            images[idx] = image
        # resize the canvas 
        self.config(width=self.width, height=self.height)
        # rescale all objects with the "all" tag
        self.scale("all",0,0,wscale,hscale)

def create_rectangle(x1, y1, x2, y2, **kwargs):
    if 'alpha' in kwargs:
        alpha = int(kwargs.pop('alpha') * 255)
        fill = kwargs.pop('fill')
        fill = root.winfo_rgb(fill) + (alpha,)
        fills.append(fill)
#        print (fill)
        image = Image.new('RGBA', (x2-x1, y2-y1), fill)
        images.append(ImageTk.PhotoImage(image))
        mycanvas.create_image(x1, y1, image=images[-1], anchor='nw')
    mycanvas.create_rectangle(x1, y1, x2, y2, **kwargs)

root.title('alpha1.py')

myframe = Frame(root)
myframe.pack(fill=BOTH, expand=YES)
WinWid=1490; WinHgt=860
mycanvas = ResizingCanvas(myframe,width=WinWid, height=WinHgt, \
                          highlightthickness=0)
mycanvas.pack(fill=BOTH, expand=YES)

create_rectangle(100, 100, 600, 600, fill='blue')
create_rectangle(300, 300, 950, 700, fill='green', alpha=.5)
create_rectangle(200, 500, 850, 820, fill='#800000', alpha=.6)
mycanvas.addtag_all("all")

root.mainloop()

注意这一行:

#            images[idx] = image

如果我删除评论#,那么红色和绿色图像就不会被绘制。仅显示图像边框。我认为这是关键,因为image 在调整大小之前应该等于images[idx]。

如果您能回答,请记住项目的下一步是抓取图像(或矩形)并将其移动到可调整大小的画布上。

【问题讨论】:

  • "resize ... image on canvas":Canvas.scale 不会调整图像大小,您必须使用,例如new_image = image.resize(... 和 Canvas.itemconfigure(..., image=new_image.
  • @stovfl 我错过了Canvas.itemconfig(。谢谢
  • @stovfl 现在一切正常! TYVM。我确实不得不求助于我自己的原始宽度、高度缩放,因为内置的 .scale(..) 方法正在返回小数宽度、先前值和新值之间的高度。你会发布一个我可以接受的答案(给你 25 分,给我 2 分)还是我应该发布我自己的答案?无论哪种方式,我都不希望这看起来是一个废弃的问题。作为副本关闭也是可以接受的。
  • 随意发布社区 wiki 答案,右下角的复选框,以显示您的解决方案。

标签: python image python-imaging-library tkinter-canvas


【解决方案1】:

感谢Stovfl's comment我能够使用:

self.itemconfig(items[idx], image=image)

改变图像的大小。不幸的是,缩放在 tkinter 中的工作方式:

# rescale all objects with the "all" tag
self.scale("all",0,0,wscale,hscale)

图片没有完全填满边框并且缺少一两个像素。所以我不得不根据原始画布的宽度和高度生成自己的缩放因子:

# images use ratio of original width/height to new width/height
wiscale = float(event.width)/self.startw
hiscale = float(event.height)/self.starth

最后为了防止垃圾收集器删除调整大小的图像,我将它分配给一个列表:

resized[idx]=image  # stop garbage collector from removing image

TL;DR

如果您想在自己的项目中使用它,这里是整个 Python 脚本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

from PIL import Image, ImageTk

root = Tk()

images = []     # to hold the newly created image
resized = []    # Resized images
fills = []      # associated list of fill attributes
items = []      # associated list of canvass item tags / ids

# a subclass of Canvas for dealing with resizing of windows
class ResizingCanvas(Canvas):
    def __init__(self,parent,**kwargs):
        Canvas.__init__(self,parent,**kwargs)

        self.bind("<Configure>", self.on_resize)
        self.height = self.winfo_reqheight()
        self.width = self.winfo_reqwidth()
        self.startw = self.width
        self.starth = self.height

    def on_resize(self,event):
        # determine the ratio of previous width/height to new width/height
        wscale = float(event.width)/self.width
        hscale = float(event.height)/self.height
        # Save new values as old values
        self.width = event.width
        self.height = event.height
        # images use ratio of original width/height to new width/height
        wiscale = float(event.width)/self.startw
        hiscale = float(event.height)/self.starth

        # resize images
        for idx, image in enumerate(images):
            fill=fills[idx]
            neww=int(image.width()*wiscale)
            newh=int(image.height()*hiscale)
            image = Image.new('RGBA', (neww, newh), fill)
            image = ImageTk.PhotoImage(image)
            self.itemconfig(items[idx], image=image)
            resized[idx]=image  # stop garbage collector from removing image

        # resize the canvas 
        self.config(width=self.width, height=self.height)
        # rescale all objects with the "all" tag
        self.scale("all",0,0,wscale,hscale)

def create_rectangle(x1, y1, x2, y2, **kwargs):
    if 'alpha' in kwargs:
        alpha = int(kwargs.pop('alpha') * 255)
        fill = kwargs.pop('fill')
        fill = root.winfo_rgb(fill) + (alpha,)
        fills.append(fill)
        image = Image.new('RGBA', (x2-x1, y2-y1), fill)
        images.append(ImageTk.PhotoImage(image))
        item=mycanvas.create_image(x1, y1, image=images[-1], anchor='nw')
        items.append(item)
    mycanvas.create_rectangle(x1, y1, x2, y2, **kwargs)

root.title('alpha1.py')

myframe = Frame(root)
myframe.pack(fill=BOTH, expand=YES)
WinWid=1490; WinHgt=860
mycanvas = ResizingCanvas(myframe,width=WinWid, height=WinHgt, \
                          highlightthickness=0)
mycanvas.pack(fill=BOTH, expand=YES)

create_rectangle(100, 100, 600, 600, fill='blue')
create_rectangle(300, 300, 950, 700, fill='green', alpha=.5)
create_rectangle(200, 500, 850, 820, fill='#800000', alpha=.6)
mycanvas.addtag_all("all")
for image in images:
    resized.append(image)

root.mainloop()

【讨论】:

    猜你喜欢
    • 2018-01-18
    • 2017-04-22
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多