在Gui中显示图像

时间:2013-01-08 11:09:44

标签: python user-interface python-imaging-library

我需要在Gui中实现一个函数,所以你按下按钮mirror,调用函数flip,然后在Gui中显示img。
假设插入mirror / flip的图片是B& W img。
我检查了flip并且它工作正常,但是当我尝试将其合并到Gui时 我错过了什么?

def flip(im):
    '''Flips a picutre horizontally, and returns a new image that is a mirror view of the original'''
    org=Image.open(im)
    new=Image.new("L",org.size)   
    for x in range(org.size[0]):
        for y in range(org.size[1]):
            pixel=org.getpixel((x,y))
            new.putpixel((org.size[0]-x-1,y),pixel)
    return new

def mirror():
    '''Flips the image like a mirror does, left to right'''
    global img
    out = Image.new('L',img.size, 'white')
    out=flip(img)
    img = out  
    display() 

def display():
    delete()
    global img
    global photo
    photo = ImageTk.PhotoImage(img)
    canvas.create_image(250, 250, image=photo)
    canvas.pack()

### GUI packing ###
g = Gui()    
g.title('PhotoPy 0.2')
global img
### canvas
canvas=g.ca(500, 500, bg='white')

### menu 
g.row(weights=[1,0,0,0])
filename = g.en(text='python.bmp', width=16)
g.bu(text='...', command=browse)
g.bu(text='Save', command=save)
g.bu(text='Load', command=load)
g.bu(text='Mirror', command=mirror)
g.endrow() 
### start
g.mainloop()

我收到此错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  ... line 87, in mirror
    out=flip(img)
  ... line 24, in flip
    org=Image.open(im)
  ... line 1956, in open
    prefix = fp.read(16)
  ... in __getattr__
    raise AttributeError(name)
AttributeError: read

1 个答案:

答案 0 :(得分:1)

假设Imagepil.Imageopen函数需要文件名或文件对象作为参数。在您的代码中img可能是None,因为您没有在任何地方设置它。

另一方面,如果你不确定你真的需要它们,你不应该为图像使用全局变量,或者一般使用全局变量。将代码重构为将图像作为属性的类。此外,在photo中将display声明为全局只是完全没必要,因为您只在display中使用它。