Locking a pygame screen [duplicate] - 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 to limit resizability in pygame [duplicate]

I have a window in pygame set up like this:
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT),pygame.RESIZABLE)
As you can see, it is resizable, and that aspect is working perfectly, but if it is too small, then you can not see everything, and so I would like to set up a limit, of for example, you can not resize the screen to have a width os less then 600, or a height of less then 400, is there a way to do that in pygame?
Thank you!
You can use the pygame.VIDEORESIZE event to check the new windows size on a resize.
What you do is on the event, you check the new windows size values, correct them according to your limits and then recreate the screen object with those values.
Here is a basic script:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480), HWSURFACE|DOUBLEBUF|RESIZABLE)
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT: pygame.display.quit()
else if event.type == VIDEORESIZE:
width, height = event.size
if width < 600:
width = 600
if height < 400:
height = 400
screen = pygame.display.set_mode((width,height), HWSURFACE|DOUBLEBUF|RESIZABLE)
EDIT: Depending on how your game graphics are drawn, you may want to resize them according to the windows resize (haven't tested that, just going after this example: http://www.pygame.org/wiki/WindowResizing)

why is my pygame widow only staying open for one second before it closes?

I am currently following a beginner pygame tutorial on YouTube here but even though I copied the code exactly from the tutorial my pygame window only stays open for about a second and then closes.
note: someone asked this question about three years ago here but it didn't fix my problem.
my code is below
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
Your script is ending and so pygame closes everything.
You have to create a loop in order for your game to continue running, with a condition to exit the loop.
You also need to initialize the display with pygame.display.init()
import pygame
pygame.init()
pygame.display.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
clock = pygame.time.Clock()
FPS = 60 # Frames per second.
# Some shortcuts for colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# For example, display a white rect
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)
# Game loop
while True:
# Ensure game runs at a constant speed
clock.tick(FPS)
# 1. Handle events
for event in pygame.event.get():
# User pressed the close button ?
if event.type == pygame.QUIT:
quit()
# Close the program. Other methods like 'raise SystemExit' or 'sys.exit()'.
# Calling 'pygame.quit()' won't close the program! It will just uninitialize the modules.
# 2. Put updates to the game logic here
# 3. Render
win.fill(BLACK) # first clear the screen
win.blit(image, rect) # draw whatever you need
pygame.display.flip() # copy to the screen

Python: Pygame installs but doesn't run well, if at all. (Mac, Mojave)

I've been trying to get pygame to work in tkinter, but all i get is two separate windows where everyone else says it works: https://stackoverflow.com/a/16550818/12221209
But when I run basic pygame code and all I get is a bouncing spaceship icon on the dock- the same with the aliens demo in terminal. Anybody know how to fix this, because it's driving me insane. All I want is a pygame window inside a tkinter window.
import pygame
import tkinter as tkinter
from tkinter import *
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
All I want is a pygame window inside a tkinter window.
I have taken the code you referenced and cleaned it up a bit to better fit Python 3 and PEP8 more closely.
Until you update your question with an example that shows the problem you have described this is the best I can do for you question.
Let me know if you have any questions.
import tkinter as tk
import pygame
import os
def pygame_update_loop():
pygame.display.update()
# Use an after loop to update the pygame window.
# set the time in milliseconds as desired.
root.after(100, pygame_update_loop)
def draw():
pygame.draw.circle(screen, (0, 0, 0), (250, 250), 125)
root = tk.Tk()
pygame_frame = tk.Frame(root, width=500, height=500)
pygame_frame.pack(side='left')
tk.Button(root, text='Draw', command=draw).pack(side='left')
os.environ['SDL_WINDOWID'] = str(pygame_frame.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
width, height = 300, 200
screen = pygame.display.set_mode((width, height))
screen.fill(pygame.Color(255, 255, 255))
pygame.display.init()
pygame_update_loop()
root.mainloop()

Cursor flashing with Tkinter and Pygame integrated in one window

Below is some code I'm testing to integrate Tkinter and Pygame together. I've managed to get a pygame display inside a Tkinter window, and also show a button ontop of this pygame display. The button simply draws a white circle. The problem starts immediately by not drawing Tkinter's configured cursor (X_cursor) when the program starts. Then, when I mouse over the button and back off of it the cursor starts to flash to pygame's default cursor and then back to Tkinter's configured cursor. Also, the cursor only reverts to pygame's default if the mouse is in motion. Otherwise, it's the correct "X_Cursor".
I'm having a hard time understanding Tkinter's system, and I'm sure the solution is in my face. I just need a little help figuring it out.
import pygame
import pygame.key
from pygame.locals import *
import tkinter as tk
from tkinter import *
import os
#colors#
BLACK = (0,0,0)
WHITE = (255, 255, 255)
GREEN = (0, 255,0)
RED = (255, 0,0)
BLUE = (0,0, 255)
#buttons#
mButton1 = (1, 0, 0)
mButton2 = (0, 1, 0)
mButton3 = (0, 0, 1)
root = tk.Tk()
root.attributes('-fullscreen', True)
root.title("This title isn't visible since it's fullscreen")
root.config(cursor = "X_cursor")
embed = tk.Frame(root, width = 1920, height = 1080) #creates embed frame for pygame window
embed.grid(columnspan = 10, rowspan = 10) # Adds grid
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
worldWindow = pygame.display.set_mode((0,0), RESIZABLE)
worldWindow.fill(BLACK)
def draw():
pygame.draw.circle(worldWindow, WHITE, (250,250), 125)
IMAGEOBJECT = PhotoImage( file = 'TESTIMAGE.gif')
buttonwin = tk.Frame(root, width = 75, height = 75)
buttonwin.grid(row =8, column = 8)
button1 = Button(root, image = IMAGEOBJECT,text = "Draw a circle", cursor = "circle", command=draw)
button1.grid(row =8 , column = 8)
pygame.display.init()
#loop until user clicks close button
done = False
clock = pygame.time.Clock()
#~~~~~~~~MAIN LOOP~~~~~~~~#
while not done:
for event in pygame.event.get():
if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and pygame.K_ESCAPE):
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
mButton = pygame.mouse.get_pressed()
if mButton == mButton1:
pos = pygame.mouse.get_pos()
print(pos)
else:
pygame.event.clear()
#limit to 60 frames per second
clock.tick(60)
#update the screen with all the draws
pygame.display.update()
root.update()
pygame.quit()
It appears to be tkinter and pygame 'fighting' over who shows the cursor. I added this to the pygame event loop to check.
elif event.type == pygame.MOUSEMOTION:
pygame.mouse.set_cursor(*pygame.cursors.diamond)
The behavior stays the same, now showing the diamond cursor while moving and 'X' Cursor when stopped. When I comment out the tkinter cursor config, I then get the windows os default cursor when motion is stopped.
The easiest solution in my mind would be to load the tkinter 'X' into pygame cursor compiler and use that as its default or under the Mouse motion event (details in link).
https://www.pygame.org/docs/ref/cursors.html
Another option I kinda liked the look of, would be to use this cursor in the mouse motion elif.
*pygame.cursors.broken_x

Pygame.transform.rotate scales istead rotation [duplicate]

This question already has answers here:
How to rotate an image around its center while its scale is getting larger(in Pygame)
(2 answers)
Closed 2 years ago.
Recently I decided to start my third pygame game.In that game the player should fire at airplanes from the cannon in the bottom of the screen,by pointing to the airplane with the mouse.I putted the code in more modules(more.py files) for easier understanding.I started by trying to get cannon barel rotate towards mouse current position.So here we go.
main.py
import pygame,sys
import screen
import constants
from pygame.locals import *
from loop import *
screen.screen = pygame.display.set_mode((800,600))
main_loop()
constatns.py
import pygame
pygame.init()
scr = pygame.display.list_modes()
resolution = (scr[0][0],scr[0][1])
angle = 0
barell = pygame.image.load("barell.png")
tux = pygame.image.load("tux.png")
tux2 = pygame.transform.scale(tux,(100,100))
loop.py
import pygame,event
import screen
import constants
import math
import random
import groups
from faster_barell import *
faster_barell = faster_barell()
faster_barell.add_to_group()
def main_loop():
while True:
mx,my = pygame.mouse.get_pos()
event.Event()
screen.screen.fill([0,0,0])
groups.barell_group.draw(screen.screen)
for t in groups.barell_group:
dx = mx - t.rect.x
dy = my - t.rect.y
angle = math.atan2(dx,dy)
angle2 = math.degrees(angle)
constants.angle = angle2
t.image = pygame.transform.rotate(constants.barell,angle2)
pygame.display.flip()
screen.py
import pygame
import constants
pygame.init()
screen = None
event.py
import pygame,sys
from pygame.locals import *
class Event(object):
def __init__(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
faster_barell.py
import pygame
import constants
import groups
class faster_barell(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = constants.barell
self.rect = self.image.get_rect()
self.rect.x = 750
self.rect.y = 550
def add_to_group(self):
groups.barell_group.add(self)
groups.py
import pygame
barell_group = pygame.sprite.Group()
Now instead of rotating pygame(I can't really explain how)scales the barell image.The barell image is just a blank(white) 10x30 image).Now here comes even more strange part.When in t.image = pygame.transform.rotate(constants.barell,angle2) I change constants.barell to constants.tux2(which is just a tux image(just for testing it won't be in the game) everything works just fine! Here is the tux image I worked with http://upload.wikimedia.org/wikipedia/commons/3/3e/Tux-G2.png .I tried to solve the problem
by changing dx and dy in math.atan2 to something else(dy,dx,-dy,dx,-dx,-dy and so on)please help I'm trying to solve this for about 6 hours(I never ask on stackoverflow unless I really can't do anything to get the code working)
Here are some helpful links:
docs
from the rotate function doc:
"Unless rotating by 90 degree increments, the image will be padded larger to hold the new size."
the solution is to crop the image after every rotation. You can crop by writing a small function that will create a new surface, and blit the middle part onto the new surface.
This problem was already solved here: so
Thank you for your answers,I tried all of them but none worked for me.
Instead i fixed it like this
pygame.transform.rotozoom(constants.barell,angle2,1) instead of pygame.transform.scale.
Thank you all :D

Categories

Resources