Pygame display on monitor's center [duplicate] - python

I need the window position right after I created a pygame window:
window = pygame.display.set_mode((width, height), 0, 32)
pygame.init()
By default, the window starts at 0,0 - but I also need x,y if the user changes the window position. Any ideas?

I need x,y coords of the pygame window - either at start or on window move. The last one is nice to have.
I figured out how to center the pygame window at the bottom of the screen:
pos_x = screen_width / 2 - window_width / 2
pos_y = screen_height - window_height
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y)
os.environ['SDL_VIDEO_CENTERED'] = '0'
Background: I have x,y coords which are screen related and I must convert the screen coords into window-local coords so that I can use them e.g. to display coords inside the pygame window or to discard coords which are outside the pygame window.
With my approach above, I knwo the initial position. But I can only use a single pygame window (because it's always at the same position) and things go wrong if the user moves the window.

It have worked for me :
import os
import pygame
x = 100
y = 45
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
pygame.init()
screen = pygame.display.set_mode((100,100))
Taken from https://www.pygame.org/wiki/SettingWindowPosition

Here is an example code that return all four corner positions:
from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT
# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]
# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")
GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right
# bottom, top, left, right: 644 98 124 644

There is a pygame.display.get_wm_info() call that gets you the Window handler -- from then on, it is using either X11 or Windows API32 to get information from the window through this handler. I didn't find any readily available information on how to do that.
So, just to be clear: there is no ordinary way to do that from within pygame. You have to proceed with another library, possibly using ctypes, after you get the window handler.
On the other hand, if you have to manipulate the window itself, maybe pygame is not the most suitable library for you to use -- you could try PyQt or even GTK+ - they also provide multmedia facilites while being more proper to operate on the level of GUI Windows and other controls
update There are ways to setup an OpenGL backend for pygame graphics, that will allow complete control of the display - including embedding it in another window, as part of a tkinter or Qt application. People that are interested can search a little deeper along those lines.

In Pygame 2, you can alternatively import the _sdl2.video to set the window position. Note that this module is experimental and could be changed in future versions.
import pygame
from pygame._sdl2.video import Window
pygame.init()
window = Window.from_display_module()
window.position = your_position_tuple
Using environment variables as mentioned in other answers is sufficient for most cases, but the downside is that once you have change the window position it will not work a second time (at least in Pygame 2).

Pygame is based on Simple DirectMedia Layer (SDL). Hence you can set SDL environment variables.
See pygame wiki - SettingWindowPosition:
You can set the position of the window by using SDL environment variables before you initialise pygame. Environment variables can be set with the os.environ dict in python.
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))

(0,0) remains the upper left corner whether the window is moved or not. If you're trying to make (0,0) stay physically where it was on the screen when the window initialized, I don't think pygame can do that. Try to make your question clearer if you want clearer answers.

To accomplish this where you don't know the monitor size of the user, use screeninfo in addition to the pygame and os packages. Screeninfo is OS-agnostic, meaning you can get the resolution of all monitors regardless of a users operating system.
import pygame
from screeninfo import get_monitors
import os
# Set the size of the pygame window
window_width = 512
window_height = 288
window_size = (window_width, window_height)
# Get the bounds of the users monitors, and select the first one
monitors = get_monitors() # Get the resolution of all of the users monitors
screen_width = monitors[0].width # Get width of first monitor found
screen_height = monitors[0].height # Get height of first monitor found
# Set the x and y coordinates of the pygame window in relation to the monitor's resolution
# (I wanted my pygame window to be located in the bottom-right of the monitor)
pos_x = screen_width - window_width # Calculate the x-location
pos_y = screen_height - window_height # Calculate the y-location
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y) # Set pygame window location
pygame.init() # Initialize the pygame window
self.screen = pygame.display.set_mode(size) # Set the location of the pygame window

Related

How to place the mouse cursor in the center of the screen using python

I use python Kivy, is it possible to put the mouse cursor in the center of the screen every time a clock event occurs?
something like:
pygame.mouse.set_pos() - I would not like to mix kivy and pygame in
my project, but if there are no alternatives, then only this option
remains
pyautogui.dragTo() - this method works but reduces performance
in the Kivy documentation I didn't find any ways other than
Window.mouse_pos = [x, y]
But it doesn't have any effect
You can do that using pyautogui.moveTo() function
height = 1920
width = 1080
pyautogui.moveTo(height / 2, width / 2)

Pygame borderless opening with some offset

When i try to open a borderless mode window it does start in the top right corner of the screen. It looks like this: http://puu.sh/ivB4y/304018da5e.jpg The code looks like this
if __name__ == "__main__":
import source.Game, pygame
pygame.mixer.pre_init(22050, 16, 2, 256)
pygame.font.init()
pygame.init()
screen = pygame.display.set_mode((1920, 1080), pygame.NOFRAME)
source.Game.Game().main(screen)
It might be worth noting that I'm running two monitors, but I've tried only running one and the problem still happens, and if I take the resolution down below native it still won't start in the top right of my screen.
Is there any way to fix such a problem?
EDIT:
I went this from the answers for anyone looking on this in the future.
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
screen = pygame.display.set_mode((1920, 1080), pygame.NOFRAME)
along with all the other .init() statements and whatnot.
Looks like you want fullscreen:
screen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN)
You might also want to turn on hardware acceleration adn double buffering using pygame.HWSURFACE | pygame.DOUBLEBUF if you are running fullscreen.
display.set_mode docs: https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode
If you actually want to keep the OS's bar on screen, then instead of going fullscreen, then ideally you would just maximize the window after creating it. However, the version of the SDL lib that Pygame is built on does not support a maximize operation (SDL 2 does). Apparently, you can control the position of the window by setting an environment variable before initializing the window (yuck), but you would still need to figure out the usable area of the desktop. Example:
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))

How can i change the position of a Surface(Game Window) with respect to computer Screen in PyGame?

I want to change the position of Game window with respect to Computer Screen. But couldn't find anything in Documentation. Please Help me.
On windows, it is possible to change the position of an initialized window using its handle (hwnd). In User32.dll there is a function called MoveWindow, that recieves a window's handle and changes its position. You can call it using python's standard ctypes module.
from ctypes import windll
def moveWin(x, y):
# the handle to the window
hwnd = pygame.display.get_wm_info()['window']
# user32.MoveWindow also recieves a new size for the window
w, h = pygame.display.get_surface().get_size()
windll.user32.MoveWindow(hwnd, x, y, w, h, False)
You can set the position that the pygame display initializes with environment variables that can be accessed with os.environ. An example from http://www.pygame.org/wiki/SettingWindowPosition?parent=CookBook:
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))
# wait for a while to show the window.
import time
time.sleep(2)
I do not think it's possible to change the position of an already initialized display, but you could quit the current display, set the environment variable, and reinitialize it.

pygame error, No video mode has been set

I am just setting up some functions for my game but my script fails to load the image
#used variables
# x, y for alien location
# nPc for the aliens image
#
#
#
#
#
#
#
#
#
#
#set up
import pygame, sys, random, time, math
from pygame.locals import *
pygame.init()
nPc = '/home/claude/Dropbox/Bowtie/Prisim/Images/Alien_Races/Standered/alien_1.png'
nPc = pygame.image.load(nPc).convert_alpha()
def loc_alien():
x = random.randint(0, 400)
y = randaom.randint(0, 400)
def spawn_alien(x, y):
screen.blit(nPc, (x, y))
when I run this I wont nothing to happen as I am not using the functions yet, but when I do run it I get this error
Traceback (most recent call last):
File "/home/claude/Dropbox/Bowtie/Prisim/Scripts/aliens.py", line 26, in <module>
nPc = pygame.image.load(nPc).convert_alpha()
error: No video mode has been set
anyone know what I'm doing wrong?
I believe that you need to call:
screen = pygame.display.set_mode((800, 600)) # change to the real resolution
this call will actually return the surface that you want to blit on. Below is the documentation from the linked resource.
pygame.display.set_mode()
Initialize a window or screen for display
set_mode(resolution=(0,0), flags=0, depth=0) -> Surface
This function will create a display Surface. The arguments passed in
are requests for a display type. The actual created display will be
the best possible match supported by the system.
The resolution argument is a pair of numbers representing the width
and height. The flags argument is a collection of additional options.
The depth argument represents the number of bits to use for color.
The Surface that gets returned can be drawn to like a regular Surface
but changes will eventually be seen on the monitor.
If no resolution is passed or is set to (0, 0) and pygame uses SDL
version 1.2.10 or above, the created Surface will have the same size
as the current screen resolution. If only the width or height are set
to 0, the Surface will have the same width or height as the screen
resolution. Using a SDL version prior to 1.2.10 will raise an
exception.
It is usually best to not pass the depth argument. It will default to
the best and fastest color depth for the system. If your game requires
a specific color format you can control the depth with this argument.
Pygame will emulate an unavailable color depth which can be slow.
When requesting fullscreen display modes, sometimes an exact match for
the requested resolution cannot be made. In these situations pygame
will select the closest compatible match. The returned surface will
still always match the requested resolution.
The flags argument controls which type of display you want. There are
several to choose from, and you can even combine multiple types using
the bitwise or operator, (the pipe “|” character). If you pass 0 or no
flags argument it will default to a software driven window. Here are
the display flags you will want to choose from:
pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
pygame.OPENGL create an OpenGL renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls
For example:
# Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])
Do not forgot to create your surface before creating variables with images in it
like this:
win = pygame.display.set_mode((576, 1024))
background_day = pygame.image.load("background-day.png").convert()
not like this:
background_day = pygame.image.load("background-day.png").convert()
win = pygame.display.set_mode((576, 1024))

Pygame Display Position

I need the window position right after I created a pygame window:
window = pygame.display.set_mode((width, height), 0, 32)
pygame.init()
By default, the window starts at 0,0 - but I also need x,y if the user changes the window position. Any ideas?
I need x,y coords of the pygame window - either at start or on window move. The last one is nice to have.
I figured out how to center the pygame window at the bottom of the screen:
pos_x = screen_width / 2 - window_width / 2
pos_y = screen_height - window_height
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y)
os.environ['SDL_VIDEO_CENTERED'] = '0'
Background: I have x,y coords which are screen related and I must convert the screen coords into window-local coords so that I can use them e.g. to display coords inside the pygame window or to discard coords which are outside the pygame window.
With my approach above, I knwo the initial position. But I can only use a single pygame window (because it's always at the same position) and things go wrong if the user moves the window.
It have worked for me :
import os
import pygame
x = 100
y = 45
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
pygame.init()
screen = pygame.display.set_mode((100,100))
Taken from https://www.pygame.org/wiki/SettingWindowPosition
Here is an example code that return all four corner positions:
from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT
# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]
# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")
GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right
# bottom, top, left, right: 644 98 124 644
There is a pygame.display.get_wm_info() call that gets you the Window handler -- from then on, it is using either X11 or Windows API32 to get information from the window through this handler. I didn't find any readily available information on how to do that.
So, just to be clear: there is no ordinary way to do that from within pygame. You have to proceed with another library, possibly using ctypes, after you get the window handler.
On the other hand, if you have to manipulate the window itself, maybe pygame is not the most suitable library for you to use -- you could try PyQt or even GTK+ - they also provide multmedia facilites while being more proper to operate on the level of GUI Windows and other controls
update There are ways to setup an OpenGL backend for pygame graphics, that will allow complete control of the display - including embedding it in another window, as part of a tkinter or Qt application. People that are interested can search a little deeper along those lines.
In Pygame 2, you can alternatively import the _sdl2.video to set the window position. Note that this module is experimental and could be changed in future versions.
import pygame
from pygame._sdl2.video import Window
pygame.init()
window = Window.from_display_module()
window.position = your_position_tuple
Using environment variables as mentioned in other answers is sufficient for most cases, but the downside is that once you have change the window position it will not work a second time (at least in Pygame 2).
Pygame is based on Simple DirectMedia Layer (SDL). Hence you can set SDL environment variables.
See pygame wiki - SettingWindowPosition:
You can set the position of the window by using SDL environment variables before you initialise pygame. Environment variables can be set with the os.environ dict in python.
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))
(0,0) remains the upper left corner whether the window is moved or not. If you're trying to make (0,0) stay physically where it was on the screen when the window initialized, I don't think pygame can do that. Try to make your question clearer if you want clearer answers.
To accomplish this where you don't know the monitor size of the user, use screeninfo in addition to the pygame and os packages. Screeninfo is OS-agnostic, meaning you can get the resolution of all monitors regardless of a users operating system.
import pygame
from screeninfo import get_monitors
import os
# Set the size of the pygame window
window_width = 512
window_height = 288
window_size = (window_width, window_height)
# Get the bounds of the users monitors, and select the first one
monitors = get_monitors() # Get the resolution of all of the users monitors
screen_width = monitors[0].width # Get width of first monitor found
screen_height = monitors[0].height # Get height of first monitor found
# Set the x and y coordinates of the pygame window in relation to the monitor's resolution
# (I wanted my pygame window to be located in the bottom-right of the monitor)
pos_x = screen_width - window_width # Calculate the x-location
pos_y = screen_height - window_height # Calculate the y-location
os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (pos_x,pos_y) # Set pygame window location
pygame.init() # Initialize the pygame window
self.screen = pygame.display.set_mode(size) # Set the location of the pygame window

Categories