【问题标题】:Python - Return type of ListPython - 列表的返回类型
【发布时间】: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 中处理以显示在窗口中。

标签: python list types undo


【解决方案1】:

您应该将last = L.pop 更改为last = L.pop()

L.pop 返回 &lt;build-in method pop of list object&gt; 但不是 PIL image object

【讨论】:

  • 非常感谢!解决方案比我想象的要简单得多!现在完美运行,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 2019-08-26
  • 2020-02-29
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多