【发布时间】: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