SevenSoda SevenSoda - 7 months ago 36
Python Question

'NoneType' object has no attribute 'show'

I'm trying to pass an image taken from ImageGrab from a class method. But it returns None. The im.show() inside takeSS() works.

import pyscreenshot as ImageGrab

class Manager():
def takeSS(self):
if __name__ == "__main__":
im = ImageGrab.grab(bbox=(0,0,1980,200))
im.show()
return im


m = Manager()

img = m.takeSS()
img.show()


console:

AttributeError: 'NoneType' object has no attribute 'show'

Answer

You have a if __name__ == "__main__": guard in the middle of your method. That's a very unusual place for that test.

Unless this script is run as the main script, your Manager.takeSS() method will always return None, leading to your error.

Remove the if test from there altogether. It may have place outside of the class though:

import pyscreenshot as ImageGrab

class Manager():
    def takeSS(self):
        im = ImageGrab.grab(bbox=(0,0,1980,200)) # X1,Y1,X2,Y2
        im.show()
        return im

if __name__ == "__main__":
    m = Manager()        
    img = m.takeSS()
    img.show()

The code in the if test is now only run if you use this module as a script. That same block will not run when you use import yourmodule.