Integrate Pygame in PySimpleGUI - python

I have a game written with a Pygame loop and it currently draws everything happening in the pygame window. I now want to integrate this window into a larger PySimpleGUI window to have nice functionality around the game. Is this possible?
I tried to use the code from here. The problem is that I get an error like this which comes from VIDEODRIVER at line 25:
pygame.error: windib not available
I changed this to 'windows' but then the Pygame window is separated from the PySimpleGUI as a different window.
Can I make the pygame loop as a window INSIDE the PySimpleGUI? Thank you.

It looks like the detached window is an open, unresolved issue with pygame 2.
If you're able to downgrade to pygame 1.9.6, the linked demo works as expected on Windows after changing the line 25 to:
os.environ['SDL_VIDEODRIVER'] = 'windows' as described.

As said there,
This line only work on windows:
os.environ['SDL_VIDEODRIVER'] = 'windib'
So make a code to skip it when the os is not Windows.
import platform
if platform.system == "Windows":
os.environ['SDL_VIDEODRIVER'] = 'windib'

Related

Python crash when using Tkinter and Pygame in one Script [duplicate]

A friend and I are making a game in pygame. We would like to have a pygame window embedded into a tkinter or WxPython frame, so that we can include text input, buttons, and dropdown menus that are supported by WX or Tkinter. I have scoured the internet for an answer, but all I have found are people asking the same question, none of these have been well answered.
What would be the best way implement a pygame display embedded into a tkinter or WX frame? (TKinter is preferable)
Any other way in which these features can be included alongside a pygame display would also work.
(Note this solution does not work on Windows systems with Pygame 2.
See Using 'SDL_WINDOWID' does not embed pygame display correctly into another application #1574. You can currently download older versions of Pygame here.)
According to this SO question and the accepted answer, the simplest way to do this would be to use an SDL drawing frame.
This code is the work of SO user Alex Sallons.
import os
import pygame
import Tkinter as tk
from Tkinter import *
root = tk.Tk()
embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
embed.grid(columnspan = (600), rowspan = 500) # Adds grid
embed.pack(side = LEFT) #packs window to the left
buttonwin = tk.Frame(root, width = 75, height = 500)
buttonwin.pack(side = LEFT)
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
screen = pygame.display.set_mode((500,500))
screen.fill(pygame.Color(255,255,255))
pygame.display.init()
pygame.display.update()
def draw():
pygame.draw.circle(screen, (0,0,0), (250,250), 125)
pygame.display.update()
button1 = Button(buttonwin,text = 'Draw', command=draw)
button1.pack(side=LEFT)
root.update()
while True:
pygame.display.update()
root.update()
This code is cross-platform, as long as the windib SDL_VIDEODRIVER line is omitted on non Windows systems. I would suggest
# [...]
import platform
if platform.system == "Windows":
os.environ['SDL_VIDEODRIVER'] = 'windib'
# [...]
Here are some links.
For embedding in WxPython An Article on pygame.org
For Embedding in WxPython An Article on the WxPython wiki
For embedding in Tkinter see this SO question
Basically, there are many approaches.
On Linux, you can easily embed any application in a frame inside another. Simple.
Direct Pygame output to a WkPython Canvas
Some research will provide the relevant code.
According to the tracebacks, the program crashes due to TclErrors. These are caused by attempting to access the same file, socket, or similar resource in two different threads at the same time. In this case, I believe it is a conflict of screen resources within threads. However, this is not, in fact, due to an internal issue that arises with two gui programs that are meant to function autonomously. The errors are a product of a separate thread calling root.update() when it doesn't need to because the main thread has taken over. This is stopped simply by making the thread call root.update() only when the main thread is not doing so.

pyautogui doesn't work in fullscreen games

I'm looking for a way to execute a spacebar click within a fullscreen game whenever a certain image appears.
My problem is that out of the game the code works perfectly, but when I run the game and leave it on screen the script doesn't work.
I searched for some solutions with a "pydirectinput" library, but the problem persists.
I'm new to Python and I don't know exactly how to get around this.
from turtle import width
from pyautogui import *
import pyautogui
import pydirectinput
while True:
if pyautogui.locateOnScreen('barra.png', region=(700, 700, 500, 500), confidence=0.8) != None:
print("Press backspace!")
pydirectinput.press('space')

module(sys) sys is not accessed pylance

I'm learning python with the book python crash course , i wrote the code for the game alien invasion , but it is not working , when i write "import sys" , the word sys is underscore and the program opens up the screen for like a millisecond and then it closes itself, i look for an answer in this site and YouTube and i haven't been able to find a solution, can anyone help? thanks in advance.
I'm using vs code on Linux mint.
this is what i wrote so far:
from settings import Settings
from ship import Ship
import sys
class AlienInvasion:
"""overall class to manage game assets and behavior"""
def __init__(self):
""" initialize the game and creates game resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""start the main loop for the game."""
while True:
self._check_events()
#whatch for keyboard and mouse events .
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
#redraw the screen during each pass through the loop.
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
It looks like there's probably an error being thrown somewhere in your script that is causing the program to stop running, and as such, close the terminal as soon as it is opened. In my experience, this only happens when you execute the script from a file browser UI by double-clicking it.
To fix this, try running the program from somewhere that will stay open, even when the program is terminated, like, for example, the built-in terminal in vscode (you can reveal by going to view > terminal). To run the program, then simply run the command:
python path/to/my/script.py
If it causes an error, you will then be able to see it printed nicely, without the terminal closing.
On another note, importing sys has nothing to do with this problem. The reason it is highlighted by pylance is that you have imported it, but then you haven't used it anywhere (for example calling a function like sys.exit()), so it thinks that the line is unnecessary. It will go away once you use the sys module somewhere else in the script.
According to your error content, I think this is caused by the fact that the file is not found, meanwhile sys is not used in your code.
Here are some reasons caused "FileNotFoundError", you could confirm one by one:
1. File name and file type
The wrong file name was inserted into the code. Please carefully check the document name.
2. Escape of Python string
In the string of file, the address string information similar to C:\user\desktop will be involved, which conflicts with the escape function in Python string, such as \n representing line feed. Use r"C:\User\Desktop" or C:\\User\\Desktop to avoid Python escaping strings.
3. Relative path problem
Generally, it is not recommended to use. In the process of Python running, the relative path is the folder that the process points to when running, and the folder is used as the file tree of the root node, that is, if you open the file by using the relative path, you can only access the file under its root node.
You could use the methods os.path.abspath() and os.path.abspath('..') provided in the OS library to view and change the absolute path where Python runs.
4. Python runtime location
If it is such a problem, you can add the following code to the head of the file:
import sys
sys.path.append("../your/target/path/")
try pip install os-sys and pip install syspath
enter link description here

Turtle window not opening with turtle.mainloop

I have the following code:
import turtle
my_pen = turtle.Turtle()
window = turtle.Screen()
window.setup(width=1000, height=1000)
window.title('Tutorial')
my_pen.color("red")
my_pen.penup()
my_pen.goto(0, 0)
window.delay(1000)
my_pen.pendown()
window.delay(100)
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(100)
my_pen.left(90)
turtle.mainloop()
When I try to run the code, the window opens and closes immediately. I am using the newest python 3.9, and I am using the newest PyCharm Community
I will attach a video of me running it and the window closing immediately
Two things: first, I don't know that the delay() method is doing anything for you, it doesn't add anything in my environment, so I'd leave it out until you've debugged the rest of the code.
Second, your code works fine for me. So I suggest you stop looking at the code and look at the environment in which you're running it. You're not simply running Python at the console but rather using some sort of IDE (Idle?). If so, you should include that information in your question.
A simple code clean up for testing purposes:
from turtle import Screen, Turtle
window = Screen()
window.setup(width=1000, height=1000)
window.title('Tutorial')
my_pen = Turtle()
my_pen.color("red")
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(100)
my_pen.left(90)
window.mainloop()

pygame fullscreen on second monitor [duplicate]

I am using pygame to program a simple behavioral test. I'm running it on my macbook pro and have almost all the functionality working. However, during testing I'll have a second, external monitor that the subject sees and the laptop monitor. I'd like to have the game so up fullscreen on the external monitor and not on the laptop's monitor so that I can monitor performance. Currently, the start of the file looks something like:
#! /usr/bin/env python2.6
import pygame
import sys
stdscr = curses.initscr()
pygame.init()
screen = pygame.display.set_mode((1900, 1100), pygame.RESIZABLE)
I was thinking of starting the game in a resizable screen, but that OS X has problems resizing the window.
Pygame doesn't support two displays in a single pygame process(yet). See the question here and developer answer immediately after, where he says
Once SDL 1.3 is finished then pygame will get support for using multiple windows in the same process.
So, your options are:
Use multiple processes. Two pygame instances, each maximized on its own screen, communicating back and forth (you could use any of: the very cool python multiprocessing module, local TCP, pipes, writing/reading files, etc)
Set the same resolution on both of your displays, and create a large (wide) window that spans them with your information on one half and the user display on the other. Then manually place the window so that the user side is on their screen and yours is on the laptop screen. It's hacky, but might a better use of your time than engineering a better solution ("If it's studpid and it works, it ain't stupid" ;).
Use pyglet, which is similar to pygame and supports full screen windows: pyglet.window.Window(fullscreen=True, screens[1])
Good luck.
I do not know if you can do this in OS X, but this is worth mentioning for the Windows users out there, if you just want to have your program to run full screen on the second screen and you are on windows, just set the other screen as the main one.
The setting can be found under Rearrange Your Displays in settings.
So far for me anything that I can run on my main display can run this way, no need to change your code.
I did something silly but it works.
i get the number of monitors with get_monitors()
than i use SDL to change the pygame window's display position by adding to it the width of the smallest screen, to be sure that the window will be positionned in the second monitor.
from screeninfo import get_monitors
numberOfmonitors = 0
smallScreenWidth = 9999
for monitor in get_monitors():
#getting the smallest screen width
smallScreenWidth = min(smallScreenWidth, monitor.width)
numberOfmonitors += 1
if numberOfmonitors > 1:
x = smallScreenWidth
y = 0
#this will position the pygame window in the second monitor
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
#you can check with a small window
#screen = pygame.display.set_mode((100,100))
#or go full screen in second monitor
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
#if you want to do other tasks on the laptop (first monitor) while the pygame window is being displayed on the second monitor, you shoudn't use fullscreen but instead get the second monitor's width and heigh using monitor.width and monitor.height, and set the display mode like
screen = pygame.display.set_mode((width,height))
display = pyglet.canvas.get_display()
display = display.get_screens()
win = pyglet.window.Window(screen=display[1])
------------------------------------------------------
screen=display[Номер монитора]
------------------------------------------------------
display = pyglet.canvas.get_display()
display = display.get_screens()
print(display) # Все мониторы которые есть

Categories