So, I am trying to create a virtual assistant in pygame, but I could not find any way of adding my search results into the window, I was planning to web scrape all the html with beatifulsoup and put that html into pygame, but the problem is that I don't know any way of how one can embed html inside pygame, and to be clear, I am not talking about embedding pygame to html, but putting html inside a pygame window
There's no way to do this directly in pygame. But you can use an external tool like wkhtmltoimage to render your HTML to an image and use that in pygame.
Here's a simple example using imgkit (a python wrapper for wkhtmltoimage):
import pygame
import imgkit
from io import BytesIO
def main():
config = imgkit.config(wkhtmltoimage=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe')
pygame.init()
screen = pygame.display.set_mode((600, 480))
html = "<style type = 'text/css'> body { font-family: 'Arial' } </style><body><h1>Html rendering</h1><div><ul><li><em>using pygame</em></li><li><strong>using imgkit</strong></li></ul></div></body>"
img = imgkit.from_string(html, False, config=config)
surface = pygame.image.load(BytesIO(img)).subsurface((0,0,280,123))
r = 0
center = screen.get_rect().center
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
screen.fill('white')
tmp = pygame.transform.rotozoom(surface, r, 1)
tmp_r = tmp.get_rect(center=center)
screen.blit(tmp, tmp_r)
r += 1
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
Related
I'm new to pygame and was copying a simple tutorial. i'm using python 3.4.2. but i'm running into several issues. Here is my code:
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
class Game(object):
def main(self,screen):
clock = pygame.time.Clock()
image = pygame.image.load('player.png').convert()
image_x=320
image_y=240
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN and event.key== pygame.K_ESCAPE:
pygame.quit()
image_x+=10
screen.fill((200,200,200))
screen.blit(image,(320,240))
screen.blit(image,(image_x,image_y))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen=pygame.display.set_mode((640,480))
Game().main(screen)
first problem is that i get an error stating "Couldn't open player.png" i have this image saved within the same folder as my .py game program. secondly when i try to exit the game, the pygame window freezes and stops responding.
It seems after a little debugging that the image file was actually in a subfolder. In order to load the image, you'll need to provide a more exact path to the file by changing this line
image = pygame.image.load('player.png').convert()
like so:
image = pygame.image.load('subfolder' + os.sep + 'player.png').convert()
Don't forget to add an import os line to the top of your file, in order to use the os.sep command, which makes directory separators cross platform.
I'm working on a project that requires me to have a viewfinder (barcode scanner).
I'm doing this with the Raspberry Pi Camera Module by the picamera python module, and I've got the whole detection and whatnot programmed.
Now I need to figure out how to display the preview from the Pi's Camera Module in a PyGame movie module.
(If there's a better way to display video from an IO Stream in PyGame, please let me know.)
The reason I need to display it in PyGame is because I'll need to overlay controls on top of the video and be able to get input from a touchscreen I'm going to use as the viewfinder/screen for the Pi/project.
As far as I can see from the pygame.movie documentation, pygame.movie only loads from a file. Is there a way that I could convert the stream into a file-like object and have PyGame play from that?
Basically put, I need a way to take the io.BytesIO stream created in this example code, and display it in PyGame.
If I understand excatly , you need to instant and infinite preview from camera module to your screen.
there is a way that I figure it out. first you must install Official V4L2 driver.
sudo modprobe bcm2835-v4l2
reference https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=62364
and than you should create a python file to compile and code this
import sys
import pygame
import pygame.camera
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640,480),0)
cam_list = pygame.camera.list_cameras()
cam = pygame.camera.Camera(cam_list[0],(32,24))
cam.start()
while True:
image1 = cam.get_image()
image1 = pygame.transform.scale(image1,(640,480))
screen.blit(image1,(0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
cam.stop()
pygame.quit()
sys.exit()
this code from http://blog.danielkerris.com/?p=225 , in this blog they did with a webcam. you define your camera module as a webcam with v4l2 driver
also you should check this tutorial https://www.pygame.org/docs/tut/camera/CameraIntro.html
I hope this will works for you
You can do this with the 'pygame.image.frombuffer' command.
Here's an example:
import picamera
import pygame
import io
# Init pygame
pygame.init()
screen = pygame.display.set_mode((0,0))
# Init camera
camera = picamera.PiCamera()
camera.resolution = (1280, 720)
camera.crop = (0.0, 0.0, 1.0, 1.0)
x = (screen.get_width() - camera.resolution[0]) / 2
y = (screen.get_height() - camera.resolution[1]) / 2
# Init buffer
rgb = bytearray(camera.resolution[0] * camera.resolution[1] * 3)
# Main loop
exitFlag = True
while(exitFlag):
for event in pygame.event.get():
if(event.type is pygame.MOUSEBUTTONDOWN or
event.type is pygame.QUIT):
exitFlag = False
stream = io.BytesIO()
camera.capture(stream, use_video_port=True, format='rgb')
stream.seek(0)
stream.readinto(rgb)
stream.close()
img = pygame.image.frombuffer(rgb[0:
(camera.resolution[0] * camera.resolution[1] * 3)],
camera.resolution, 'RGB')
screen.fill(0)
if img:
screen.blit(img, (x,y))
pygame.display.update()
camera.close()
pygame.display.quit()
When i run the code it play only the .wav file
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
pygame.mixer.music.stop()
someone know what i should do for the background.ogg to be played too?
Remove this line:
pygame.mixer.music.stop()
Basically, you're loading and playing the background noise, and then immediately stopping it. I also suggest you create a main loop, like so:
import pygame
from pygame.locals import *
# This makes sure that you're not importing the module.
if __name__ == "__main__":
# Create surface
size = width, height = (500, 400)
# You don't need the extra arguments
window = pygame.display.set_mode(size)
# Do sound stuff
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
# This is your main loop.
running = True
while running:
# Check if escape was pressed
Most of the time people just check if Escape was pressed in their main loop (if it was pressed, they set running = False and exit the program).
I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
Hi after much research I cant find the answer.
running mac osx 10.8.4 python 2.7.5 and pygame 1.9.2.
all modules were found in the build of pygame and reinstalling doesnt fix the issue
while running:
import pygame
import math
import random
black = (0,0,0)
red = (255,0,0)
white = (255,255,255)
blue = (0,0,255)
green = (0,255,0)
pygame.init()
print pygame.image.get_extended()
size = (1000,700)
screen = pygame.display .set_mode(size)
pygame.display.set_caption("My game")
done = False
clock = pygame.time.Clock()
background_image = pygame.image.load("red_x.png").convert()
while done == False:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT
# ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT
# ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
screen.fill(black)
screen.blit(background_image,[0,0])
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
pygame.display.flip()
clock.tick(20)
pygame.quit()
I get a file is not a valid windows BMP error.
pygame.images.get_extended() returns 0
and
try:
import SDL_image
print "Loaded SDL_image"
except:
print "Failed to import SDL_image"
try:
import libpng
print "Loaded libpng"
except:
print "Failed to import libpng"
returns both failed import messages. I think thats all the tests i saw while searching for this and all of their solutions didnt work.
I had the same problem, but I managed to solve it installing the following version of Pygame: http://pygame.org/ftp/pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg