2012-06-05 33 views
0

我想为我的图像编辑程序实现撤消功能。下面是我的代码部分:Python - 返回类型的列表

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 

我猜的错误是指可变last我传递给displayimundo不是PIL图像对象,因此它不能添加到PhotoImage。现在有没有适合我的解决方案?请告诉我,如果你有任何建议。

+0

我会通过看这个答案http://stackoverflow.com/questions/2006404/making-undo-in启动-python – ditkin

+0

我之前读过这篇文章,我认为这很相似。但是,由于下面的答案,我现在修好了! –

+0

任何具体的原因,你存储你的PIL图像与全局列表中的PhotoImage分离?似乎跟踪这个建议并将它们存储在PhotoImage上会更容易跟踪? http://effbot.org/tkinterbook/photoimage.htm,然后可能存储一堆PhotoImage实例 – jdi

回答

4

你应该改变last = L.poplast = L.pop()

L.pop回报<build-in method pop of list object>但不是PIL image object

+0

非常感谢!解决办法比我想象的更简单!现在它完美的工作,谢谢。 –