在桂中显示图像 [英] Showing image in Gui

查看:57
本文介绍了在桂中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Gui中实现一个功能,因此您按下按钮mirror,它会调用功能flip,并在Gui中显示img.
假定插入到mirror/flip的图片是B& W img.
我检查了flip,它工作正常,但是当我试图在Gui中将其合并时,却不能. 我想念什么?

I need to implement a function in Gui so you press the buttuon mirror, it calls the function flip, and display the img in the Gui.
Assume that the picture inserted to mirror/flip is B&W img.
I checked flip and it works fine, but not when Im trying to combine it in the Gui.
what am I missing?

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

推荐答案

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

Assuming Image is pil.Image, the open function expects a file name or a file object as the argument. In your code img is probably None as you don't set it anywhere.

另一方面,如果您不确定确实需要全局变量,则不要为图像使用全局变量,也不要一般使用全局变量.将代码重构为以图像为属性的类.另外,在display中将photo声明为全局变量是完全不必要的,因为无论如何只能在display中使用它.

On another note, you shouldn't use a global variable for the image, or use global variables in general, if you're not sure you really need them. Refactor your code into a class that has the image as an attribute. Also, declaring photo as global in display is just plain unneccessary as you only use it in display anyways.

这篇关于在桂中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆