Fish swim in pygame - python-2.7

I want to use the python pygame module to make a 2D "fishtank".
Basically I will load a jpg image as background and load a gif animated image depicting fish swimming and make it move.
I know how to make an static image move but how to make a gif image move while the image itself is animated.
I have PIL installed, do sure if need to use it.
If that does not work, I can also break apart the gif file into several static frames and cyclically make each of them show on screen. When the latter one is posted, the former one needs to be removed, how to remove it ?

Here is a class I used in my name to get PyGame animation to work:
class Animation(pygame.sprite.Sprite):
def __init__(self, img, fps = 6):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Slice source image to array of images
self.images = self.loadSliced(img)
# Track the time we started, and the time between updates.
# Then we can figure out when we have to switch the image.
self._start = pygame.time.get_ticks()
self._delay = 1000 / fps
self._last_update = 0
self._frame = 0
self.image = self._images[self._frame]
def loadSliced(w, h, filename):
"""
Pre-conditions:
Master can be any height
Sprites frames must be the same width
Master width must be len(frames)*frames.width
Arguments:
w -- Width of a frame in pixels
h -- Height of a frame in pixels
filename -- Master image for animation
"""
images = []
if fileExists( img, "Animation Master Image"):
master_image = pygame.image.load(filename).convert_alpha()
master_width, master_height = master_image.get_size()
for i in range(int(master_width/w)):
images.append(master_image.subsurface((i*w, 0, w, h)))
return images
def update(self, t):
# Note that this doesn't work if it's been more than self._delay
# time between calls to update(); we only update the image once
# then. but it really should be updated twice
if t - self._last_update > self._delay:
self._frame += 1
if self._frame >= len(self._images):
self._frame = 0
self.image = self._images[self._frame]
self._last_update = t
self.image = self._images[self._frame]
self._last_update = t
def getFrame(self, screen):
# Update Frame and Display Sprite
self.update(pygame.time.get_ticks())
return self.image

Related

Tkinter Background not showing transparent

Hey im a newbie in python in my code there is a animated gif that play whenever i run the code. The gif image is actually transparent when open in adobe etc. but the problem is when i run the code.The frame which is the color gray included in the gif.I want to remove the color gray so that the only thing that can see is my only animated gif
This is my code:
# mimic an animated GIF displaying a series of GIFs
# an animated GIF was used to create the series of GIFs
# with a common GIF animator utility
import time
from Tkinter import *
root = Tk()
imagelist = ["dog001.gif","dog002.gif","dog003.gif"]
# extract width and height info
photo = PhotoImage(file=imagelist[0])
width = photo.width()
height = photo.height()
canvas = Canvas(width=width, height=height)
canvas.create_line(0,240,640,240, fill='blue')
canvas.pack()
# create a list of image objects
giflist = []
for imagefile in imagelist:
photo = PhotoImage(file=imagefile)
giflist.append(photo)
# loop through the gif image objects for a while
for k in range(0, 10):
for gif in giflist:
canvas.delete(ALL)
canvas.create_image(width/2.0, height/2.0, image=gif)
canvas.update()
time.sleep(0.1)
root.mainloop()[![enter image description here][1]][1]
dog001.gif
dog002.gif
dog003.gif
As described here, making a Tkinter window transparent is possible, but depends on your OS.
If you are on Windows, just add the following lines after creating the root:
root = Tk()
# Hide the root window drag bar and close button
root.overrideredirect(True)
# Make the root window always on top
root.wm_attributes("-topmost", True)
# Define a transparent color
root.wm_attributes("-transparentcolor", '#eeefff')
Then set your canvas' background color as the transparent color defined above:
canvas = Canvas(width=width, height=height, bg='#eeefff', highlightthickness=0)

put label in frame without class etc

How can I get the label in this simple frame? I tried to make the label go to the frame but then I only see the label and the frame disappears.
Notice here that I want 2 different sizes. The root.geometry("200x200") which is gray. I also am putting a Frame in the root of 100w x 100h. Run the code, I can see both color areas great. But my label does not appear, in the Frame darkgray area. Which is my problem.
from Tkinter import *
root=Tk()
root.geometry("200x200")
root.title("basicGUI")
root.configure(background="gray")
frame = Frame(width=100, height=100,
bg="darkgray")
frame.pack()
mylabel=Label(text="anyWord")
mylabel.pack()
"""
# darkgray frame disappears
mylabel=Label(frame, text="anyWord")
mylabel.pack(side = LEFT)
"""
mainloop()
Thanks to Lafexlos, a one line addition solved my problem.
from Tkinter import *
root=Tk()
root.geometry("200x200")
root.title("basicGUI")
root.configure(background="gray")
frame = Frame(width=100, height=100,
bg="darkgray")
frame.pack_propagate(0) #adding line solves problem
frame.pack()
mylabel1=Label(frame, text="anyWord")
mylabel1.pack(side = TOP)
mainloop()

pygame my picture wont show up on my window

import pygame
import sys
import os
from pygame.locals import *
#Allows for the editing of a window
pygame.init()
#Sets screen size
window = pygame.display.set_mode((800,600),0,32)
#Names the window
pygame.display.set_caption("TEST")
#Types of colors (red,green,blue)
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
yellow = (255,255,0)
red = (255,0,0)
purple = (255,0,255)
lightblue = (0,255,255)
white = (255,255,255)
pink = (255,125,125)
mif="climb.PNG"
mif=pygame.image.load(mif).convert()
#Loop
gameLoop = True
while gameLoop:
pygame.display.flip() #must flip the image o the color is visable
window.blit(mif, (0,0))
window.fill(black) #used to fill the creen with the certian color variables
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop=False #Allows the user to exit the loop/game
pygame.quit() #quit the pygame interface
exit(0)
When I select run my yellow window pops up but no image...
I'm new to pygame and python so maybe I just did something wrong?
Is there a specific place that I should have my image saved to?
I'm running on a windows 8 hp ENVY...
I just want to learn what I'm doing wrong so I don't make the error again. (I should also add that I have tried many different pictures and some where not able to be located.)
First fill window with black color window.fill(black),
then put image on it window.blit(mif, (0,0)),
and last send it to your graphic card (and on your monitor) pygame.display.flip()
window.fill(black)
window.blit(mif, (0,0))
pygame.display.flip()
If your image is as big as window then you don't need to use fill(black).
You can keep image in the same folder with script. Or you can create subfolder only for image to have order in folders.
If you call this folder images then you have to add this to filenames images/climb.PNG.
BTW: better use / than \ in path because \n in path can be interpreted as ENTER/new line as in any text.
But the most properly is:
import os
filename = os.path.join('images', 'climb.PNG')

Stop frames from resizing in respect to the content (Tkinter + Python2.7)

I am trying to make something like this using frames:
And this is my code so far: # I am trying to put the frames in the certain location only, and not fill the entire display
from Tkinter import *
class Menu():
def display(self):
self.canvas = Canvas(width=1200,height=700)
self.canvas.grid()
self.controlcanvas = Canvas(self.canvas,width=850,height=200)
self.controlcanvas.place(x=348,y=107)
indexframe = Frame(self.controlcanvas)
titleframe = Frame(self.controlcanvas)
readCframe = Frame(self.controlcanvas)
commentCframe = Frame(self.controlcanvas)
indexframe.pack(side=LEFT)
titleframe.pack(side=LEFT)
readCframe.pack(side=LEFT)
commentCframe.pack(side=LEFT)
dummyindex = Label(indexframe,text="#").grid(row=0,column=0)
dummytitle = Label(titleframe,text="Title").grid(row=0,column=1)
dummyreadC = Label(readCframe,text="Read Count").grid(row=0,column=2)
dummycommentC = Label(commentCframe,text="Comments").grid(row=0,column=3)
mainloop()
m = Menu()
m.display()
The problem here is that the # Title Read Count and Comments resize the frame into small one.
I want the frames to retain their original geometry so that I could create something like the picture.
Any help?
Frame has a list of config options that handle its properties like size and border. When you create the frame, you can specify these options:
indexframe = Frame(self.controlcanvas, height=400, width=200, borderwidth=2)
or you can access them later via:
indexframe.config(borderwidth=2)
Take a look at the method documentation for more options.

Pygame - pygame.mouse.get_pos problems

The problem isn't errors, it's just that i'm trying to get this crosshair image to follow the mouse about the screen, I succeeded but it's leaving a trail of the same image behind it so the screen eventually becomes spammed with the image, heres the code:
import sys, pygame;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
pygame.init()
screen = pygame.display.set_mode((800, 600))
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print("test1")
elif event.type == MOUSEBUTTONDOWN and event.button == 3:
print("test3")
pos = pygame.mouse.get_pos() #Here is the mouse following code
screen.blit(mousec, (pos)) #Setting image to pos of mouse.. atleast I think I am
pygame.display.update()
Your code has no problem....it is doing what you are telling it.
However for any image drawn a new background is created (along with the image) that is set as the new background it self so the background needs to be erased and set to default before the function pygame.display.update() or pygame.display.flip() is called.
more information here
So basically all you can do is create a new background by taking a image (800x600) ('background.png').
Load it:
bk = pygame.image.load('background.png').convert_alpha()
Blit it before blitting other moving objects.screen.blit(bk, (0,0))pos = pygame.mouse.get_pos() #Here is the mouse following code
screen.blit(mousec, (pos)) #Setting image to pos of mouse
pygame.display.update()
Adding a background to your game provides the game a complete touch but if you do not want to add it then the simplest thing you can do is fill your screen with a color every time the while loop is called.
So just after the while loop starts add this:
screen.fill(Color("black"))