Pyautogui error on windows "KeyError: ‘DISPLAY’"

  pyautogui, python, windows

I have already used pyautogui on a Mac os system before without any trouble, but now I’m trying on a windows 10 machine running this code:

import pyautogui
print(pyautogui.position())

And I get the following error:

Traceback (most recent call last):
  File "screenshot.py", line 1, in <module>
    import pyautogui  File "/home/cj/.local/lib/python3.8/site-packages/pyautogui/__init__.py", line 241, in <module>
    import mouseinfo
  File "/home/cj/.local/lib/python3.8/site-packages/mouseinfo/__init__.py", line 223, in <module>
    _display = Display(os.environ['DISPLAY'])  File "/usr/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'DISPLAY'

I have already tried with os.environ[‘DISPLAY’] = ‘:0’ but it still doesn’t work.
It would just return this

Traceback (most recent call last):
  File "screenshot.py", line 1, in <module>
    import pyautogui
  File "/home/cj/.local/lib/python3.8/site-packages/pyautogui/__init__.py", line 241, in <module>
    import mouseinfo
  File "/home/cj/.local/lib/python3.8/site-packages/mouseinfo/__init__.py", line 223, in <module>
    _display = Display(os.environ['DISPLAY'])
  File "/home/cj/.local/lib/python3.8/site-packages/Xlib/display.py", line 89, in __init__
    self.display = _BaseDisplay(display)
  File "/home/cj/.local/lib/python3.8/site-packages/Xlib/display.py", line 71, in __init__
    protocol_display.Display.__init__(self, *args, **keys)
  File "/home/cj/.local/lib/python3.8/site-packages/Xlib/protocol/display.py", line 
89, in __init__
    self.socket = connect.get_socket(name, protocol, host, displayno)
  File "/home/cj/.local/lib/python3.8/site-packages/Xlib/support/connect.py", line 87, in get_socket
    return mod.get_socket(dname, protocol, host, dno)
  File "/home/cj/.local/lib/python3.8/site-packages/Xlib/support/unix_connect.py", line 127, in get_socket
    raise error.DisplayConnectionError(dname, str(val))
Xlib.error.DisplayConnectionError: Can't connect to display ":0": [Errno 111] Connection refused

Any suggestion?

Source: Windows Questions

One Reply to “Pyautogui error on windows "KeyError: ‘DISPLAY’"”

LEAVE A COMMENT