【发布时间】:2012-06-09 01:55:06
【问题描述】:
我正在尝试为我的图像编辑程序实现撤消功能。以下是我的部分代码:
def displayim(root, panel, img, editmenu):
global image, L
L.append(img)
print(len(L))
if (len(L) > 1):
editmenu.entryconfig(0, state=NORMAL)
else:
editmenu.entryconfig(0, state=DISABLED)
image1 = ImageTk.PhotoImage(img)
root.geometry("%dx%d+%d+%d" % (img.size[0], img.size[1], 200, 200))
panel.configure(image = image1)
panel.pack(side='top', fill='both', expand='yes')
panel.image = image1
image = img
def undo(root, panel, editmenu):
global L
i = len(L)
del L[i-1]
last = L.pop
displayim(root, panel, last, editmenu)
我的想法是,当调用任何打开图像或为图像添加效果的函数时,它将通过调用displayim来显示结果。参数editmenu 确保如果没有要撤消的操作,undo 命令将被禁用。变量L 是一个列表,用于存储每个函数调用后图像的状态。当调用undo 函数时,它会删除列表中的最后一项以及最后一项之前的一项(现在成为最后一项),并将这个新的最后一项传递给displayim,以便程序可以显示图像的先前状态并将其再次添加到列表中。
但是,当我尝试使用undo 函数时,我得到了错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
File "D:\Users\ichigo\workspace\SS2\test\main.py", line 26, in <lambda>
editmenu.add_command(label="Undo", command=lambda:file.undo(root, panel, editmenu), state=DISABLED)
File "D:\Users\ichigo\workspace\SS2\test\file.py", line 51, in undo
displayim(root, panel, last, editmenu)
File "D:\Users\ichigo\workspace\SS2\test\file.py", line 39, in displayim
image1 = ImageTk.PhotoImage(img)
File "D:\Python32\lib\site-packages\PIL\ImageTk.py", line 110, in __init__
mode = Image.getmodebase(mode)
File "D:\Python32\lib\site-packages\PIL\Image.py", line 225, in getmodebase
return ImageMode.getmode(mode).basemode
File "D:\Python32\lib\site-packages\PIL\ImageMode.py", line 50, in getmode
return _modes[mode]
TypeError: unhashable type: 'list'
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage object at 0x01B1AA50>> ignored
我猜这个错误意味着我从undo 传递给displayim 的变量last 不是PIL 图像对象,所以它不能被添加到PhotoImage。我现在有什么解决方案吗?如果您有任何建议,请告诉我。
【问题讨论】:
-
我以前读过那个,我认为这很相似。但是感谢下面的答案,我现在修复了它!
-
您将 PIL 图像与 PhotoImage 分离存储在全局列表中的任何具体原因?如果您遵循此建议并将它们存储在 PhotoImage 上,似乎会更容易跟踪? effbot.org/tkinterbook/photoimage.htm,然后可能存储了一堆 PhotoImage 实例
-
@jdi 我必须以这种方式存储它,因为 PIL 图像是由效果函数返回的。然后这些将在
displayim中处理以显示在窗口中。