2013-01-08 58 views
0

我需要在Gui中实现一个功能,所以你按下了buttuon mirror,它调用函数flip,并在Gui中显示img。
假设插入到mirror/flip的图片是B & W img。
我检查了flip,它工作正常,但不是当我试图将它结合在Gui
我错过了什么?在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

假设Imagepil.Image,该open函数需要一个文件名或文件对象作为参数。在您的代码img可能是None,因为您不设置它在任何地方。

在另一个说明中,如果您不确定是否真的需要它们,则不应在图像中使用全局变量,也不要使用全局变量。将您的代码重构为具有图像作为属性的类。另外,在display中声明photo为全球性的仅仅是不必要的,因为反正你只在display中使用它。

+0

好的,但我不知道如何解决它,所以它可以工作.. 整个'全球img'的东西是我得到的,因为它是,不应该改变它。例如,我在代码中具有此功能: def bnw(): ''''将图像转换成黑白''' img = img.convert(mode ='L') display ()' – user1816377

+0

,它工作正常 – user1816377

+1

当然,它的工作原理,它只是非常糟糕的设计...为了修复你的'翻转'功能,从它删除'打开'调用,并确保你传入它已经是打开图像。这意味着你可能必须在全球范围内打开一次图像,如果你还没有这样做。 – l4mpi