I had the same problem and found the solution. The reason of the error is not passing the MIT-MAGIC-COOKIE-1 to the root. This file is stored on ~/.Xauthority. You have three options.
1) Quick fix would be loading all the user environment
$ sudo -E python myscript.py
-E option would load root shell environments from user's home directory. So, ~/.Xauthority of the user will be read. However, this is kinda brute force and not really recommended for security concern.
2) list the key and load it to root /root/.Xauthority
Another way to directly load the key to root .Xauthority.
pi@RPi-Dev:~$ xauth list
RPi-Dev/unix:10 MIT-MAGIC-COOKIE-1 5cxxxxxxxxxxxxxxxxxxxxxxxxxxx3d3
pi@RPi-Dev:~$ sudo -s
root@RPi-Dev:/home/pi# xauth add RPi-Dev/unix:10 MIT-MAGIC-COOKIE-1 5c5cxxxxxxxxxxxxxxxxxxxxxxxxxxxd3
3) setup and passing XAUTHORITY environment value.
You can specify .Xauthority file with XAUTHORITY, however, by default it's not set and just load the file from ~/.Xauthority. So, give sudo option this way.
$ sudo XAUTHORITY=${HOME}/.Xauthority python myscript.py
root will get XAUTHORITY=/home/(user)/.Xauthority, and read the file accordingly.