Bring a pygame window to front - python

from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame # import after disabling prompt
screen = pygame.display.set_mode((800, 800))
screen.fill((50, 50, 50)) # Dark gray color
pygame.display.update()
Yes, I did my research already, and couldn't find anything helpful: hence this question.
Every time I run the program the pygame window opens below other windows. I want it to behave in 2 ways based on code: Pin the window on top and spawn on top but no pin.

Here is the simplest solution I found:
(It also requires tkinter to get system screen metrics)
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame # import after disabling environ prompt
from win32gui import SetWindowPos
import tkinter as tk
root = tk.Tk() # create only one instance for Tk()
root.withdraw() # keep the root window from appearing
screen_w, screen_h = root.winfo_screenwidth(), root.winfo_screenheight()
win_w = 250
win_h = 300
x = round((screen_w - win_w) / 2)
y = round((screen_h - win_h) / 2 * 0.8) # 80 % of the actual height
# pygame screen parameter for further use in code
screen = pygame.display.set_mode((win_w, win_h))
# Set window position center-screen and on top of other windows
# Here 2nd parameter (-1) is essential for putting window on top
SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 1)
# regular pygame loop
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
done = True

Related

How Do I make sure my pygame window stays at the top

I am made a little window that helps me play a game. But when I click somewhere else the window just minimizes or goes to the back. How do I make sure that my pygame window stays on top of the screen?
My answer is taken from Bring a pygame window to front
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame # import after disabling environ prompt
from win32gui import SetWindowPos
import tkinter as tk
root = tk.Tk() # create only one instance for Tk()
root.withdraw() # keep the root window from appearing
screen_w, screen_h = root.winfo_screenwidth(), root.winfo_screenheight()
win_w = 250
win_h = 300
x = round((screen_w - win_w) / 2)
y = round((screen_h - win_h) / 2 * 0.8) # 80 % of the actual height
# pygame screen parameter for further use in code
screen = pygame.display.set_mode((win_w, win_h))
# Set window position center-screen and on top of other windows
# Here 2nd parameter (-1) is essential for putting window on top
SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 1)
# regular pygame loop
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
done = True
Hope it helps!☺

Strange "X" on PyOpenGL + PyGame

I'm trying to create a PyOpenGL "Hello World" project. I made some code that generates a cube to me and displays it on the screen, the problem is it doesn't show a cube, it show a strange flat 2D "X". I am almost sure that the problem is with my PyGame settings because I've tried to display a simple line and it, actually, nothing was displayed.
I don't know if this is a useful information, but my operational system is Linux - Pop!_os.
FULL CODE: https://github.com/caastilho/PyOpenGL-Problem
LAUNCHER.PY
All the PyGame display settings are storage here
import pygame
from pygame import event as events
from pygame import display
import sys, os
from screeninfo import get_monitors
from canvas import setup, draw
# Root class: "Launcher"
class Launcher:
def __init__(self):
pygame.init()
# Create default settings
self.title = "PyGame Screen"
self.size = (500, 500)
self.flags = 0
setup(self)
self.__setupSurface()
# Run screen
self.__runSurface()
# Setup environment
def __setupSurface(self):
"""Setup environment."""
# Get the main monitor dimensions
for monitor in get_monitors():
if monitor.x == monitor.y == 0:
middle_x = (monitor.width - self.size[0]) // 2
middle_y = (monitor.height - self.size[1]) // 2
offset = f"{middle_x},{middle_y}"
# Setup window
os.environ["SDL_VIDEO_WINDOW_POS"] = offset
display.set_caption(self.title)
self.surface = display.set_mode(self.size, self.flags)
# Run environment
def __runSurface(self):
"""Run environment."""
while True:
draw(self)
pygame.time.wait(10)
# Close condition
for event in events.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Run launcher
if __name__ == "__main__":
Launcher()
CANVAS.PY
All the draw functions are storage here
from pygame import display
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from Shapes.shape import OpenGL_Cube # Imports the cube class
cube = None
clear_flags = None
# Setup canvas
def setup(app):
global cube, clear_flags
app.size = (1280, 720) # Setup window size
app.title = "PyOpenGl" # Setup window title
app.flags = DOUBLEBUF|OPENGL # Setup PyGame flags
# Setup OpenGL environment
clear_flags = GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT
gluPerspective(45, (app.size[0]/app.size[1]), 0.1, 50)
glTranslatef(0, 0, -5)
glRotatef(0, 0, 0, 0)
# Setup objects
cube = OpenGL_Cube()
# Run canvas
def draw(app):
cube.draw()
display.flip()
glClear(clear_flags)
OUTPUT
EDIT
Just to clarify, the lines of code that i am using to display the cube edges are this one:
glBegin(GL_LINES)
for node in nodes: # Where node = (x, y, z)
glVertex3fv(node)
glEnd
The perspective projection and the model view matrix is never set, because you invoke the function setup before self.__setupSurface().
Note, for any OpenGL instruction a valid and current OpenGL Context is requried, else the instruction has no effect. The OpenGL Context is created when the pygame display surface is generated (display.set_mode()). Hence setup has to be invoked after self.__setupSurface():
class Launcher:
# [...]
def __init__(self):
pygame.init()
# [...]
self.size = (1280, 720)
self.title = "Marching Cubes"
self.flags = DOUBLEBUF|OPENGL
# create OpenGL window (and make OpenGL context current)
self.__setupSurface()
# setup projection and view
setup(self)
# Setup canvas
def setup(app):
global cube, clear_flags
# Setup OpenGL environment
clear_flags = GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT
gluPerspective(45, (app.size[0]/app.size[1]), 0.1, 50)
glTranslatef(0, 10, -5)
glRotatef(0, 0, 0, 0)
# Setup objects
cube = OpenGL_Cube()

How to make a Pygame Zero window full screen?

I am using the easy-to-use Python library pgzero (which uses pygame internally) for programming games.
How can I make the game window full screen?
import pgzrun
TITLE = "Hello World"
WIDTH = 800
HEIGHT = 600
pgzrun.go()
Note: I am using the runtime helper lib pgzrun to make the game executable without an OS shell command... It implicitly imports the pgzero lib...
Edit: pgzero uses pygame internally, perhaps there is a change the window mode using the pygame API...
You can access the pygame surface which represents the game screen by screen.surface and you can change the surface in draw() by pygame.display.set_mode(). e.g.:
import pgzrun
import pygame
TITLE = "Hello World"
WIDTH = 800
HEIGHT = 600
def draw():
screen.surface = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
pgzrun.go()
Or switch to fullscreen when the f key is pressed respectively return to window mode when the w key is pressed in the key down event (on_key_down):
import pgzrun
import pygame
TITLE = "Hello World"
WIDTH = 800
HEIGHT = 600
def on_key_down(key):
if key == keys.F:
screen.surface = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
elif key == keys.W:
screen.surface = pygame.display.set_mode((WIDTH, HEIGHT))
pgzrun.go()
import pgzrun
import pygame
TITLE = "Hello World"
WIDTH = 800
HEIGHT = 600
def draw():
screen.surface = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
pgzrun.go()

pygame not displaying my image

i started learning pygame and i followed some tutorials to make simple hello world project and it works but when i do it my self trying to display my image on the window nothing happen!
this is my code
__author__ = 'mohammed'
import sys
import pygame
import color
# -----------setup------------------------
pygame.init() # start pygame
screensize = (800, 600) # variable that we will use to declare screen size
screen = pygame.display.set_mode(screensize) # set the screen size
pad = pygame.image.load('2.png')
x = 100
y = 100
# -----------setup------------------------
# -------------------main loop------------
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(pad, (x, y))
screen.fill(red)
pygame.display.update()
i am importing my file that contain colors and their rgb :
red = (255, 0, 0)
It looks like you're filling the screen after the image is drawn, covering the image. Try switching the order of the rows:
screen.blit(pad, (x, y))
and
screen.fill(red)

How to detect resizeable window state in pygame and de-maximize it in Linux?

I have an application built in python with use of pygame that initially displays a login screen at a set size which is not RESIZABLE and then when user logs into the game the saved settings are being used to transform the window size. The window is turned into RESIZABLE after login. If user logs out the window is changed back to the initial size without RESIZABLE flag. Everything is OK as long as the user logs out from normal window, but when user hits the maximize button and then logs out in some distros the window still stays maximized and the login screen is being painted in a top left corner of the window.
And here comes the question, is there a way of detecting whether the window has been maximized so I can de-maximize it before sizing down?
I couldn't find anything that would help me with this in the pygame docs or anywhere online. I have found a way of getting a "handle" to the window by using:
pygame.display.get_wm_info()['window']
but not sure where to take it from here.
The way I set the sizes:
self.screen = pygame.display.set_mode((800, 480)) #login screen
self.screen = pygame.display.set_mode(user_saved_size, pygame.RESIZABLE) #game screen
get_wm_info()['wmwindow'] gives you windowID in Windows Manager (X.org) but it is "outside" of PyGame. Maybe with python library Xlib you could do something.
EDIT:
I tried example in Setting the window dimensions of a running application to change terminal size and it works but it don't change PyGame window size. I tried xlib to get PyGame window caption and it works but I could not set PyGame window caption.It seems PyGame doesn't respect new caption.
I use this code to test PyGame window caption - it can get caption but it can't set caption.
import sys
import pygame
from pygame.locals import *
import Xlib
import Xlib.display
WIDTH, HEIGHT = 1500, 300
pygame.init()
screen = pygame.display.set_mode((800,600),0,32)
print "wm_info:", pygame.display.get_wm_info()
print " window:", pygame.display.get_wm_info()['window']
print "fswindow:", pygame.display.get_wm_info()['fswindow']
print "wmwindow:", pygame.display.get_wm_info()['fswindow']
display = Xlib.display.Display()
root = display.screen().root
#windowID = root.get_full_property(display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0]
#print "Xlib windowID:", windowID
#window = display.create_resource_object('window', windowID)
window = display.create_resource_object('window', pygame.display.get_wm_info()['window'])
window.configure(width = WIDTH, height = HEIGHT)
print "Xlib window get_wm_name():", window.get_wm_name()
window = display.create_resource_object('window', pygame.display.get_wm_info()['fswindow'])
window.configure(width = WIDTH, height = HEIGHT)
print "Xlib fswindow get_wm_name():", window.get_wm_name()
window = display.create_resource_object('window', pygame.display.get_wm_info()['wmwindow'])
window.configure(width = WIDTH, height = HEIGHT)
print "Xlib wmwindow get_wm_name():", window.get_wm_name()
print
print "Xlib wmwindow set_wm_name(hello world of xlib)"
window.set_wm_name("hello world of xlib")
display.sync()
print "Xlib wmwindow get_wm_name():", window.get_wm_name()
# --------------
fpsClock = pygame.time.Clock()
RUNNING = True
while RUNNING:
for event in pygame.event.get():
if event.type==QUIT:
RUNNING = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
RUNNING = False
fpsClock.tick(25)
# --------------
pygame.quit()
sys.exit()
I use this code to change window size - it works in terminal and DreamPie (python shell):
# https://unix.stackexchange.com/questions/5999/setting-the-window-dimensions-of-a-running-application
WIDTH, HEIGHT = 1500, 300
import Xlib
import Xlib.display
display = Xlib.display.Display()
root = display.screen().root
windowID = root.get_full_property(display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0]
window = display.create_resource_object('window', windowID)
window.configure(width = WIDTH, height = HEIGHT)
display.sync()
#windowIDs = root.get_full_property(display.intern_atom('_NET_CLIENT_LIST'), Xlib.X.AnyPropertyType).value
#for windowID in windowIDs:
# window = display.create_resource_object('window', windowID)
# name = window.get_wm_name() # Title
# pid = window.get_full_property(display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) # PID

Categories