Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spritesheets in Tkinter

I'm writing a GUI in Python's Tkinter, and I can't find how to use the canvas's create_image method to only draw a single sprite from a spritesheet. Thanks in advance to anyone who can tell me what I need to do for this!

like image 586
Derek Peirce Avatar asked May 16 '13 05:05

Derek Peirce


People also ask

How do you use Spritesheets?

To use a sprite sheet, you load the sprite sheet as a single large image, and then you load the individual images from the sprite sheet image. This turns out to be much more efficient than loading a bunch of separate image files.


1 Answers

First of all, I strongly recommend you to use Pygame, since it has a concrete module for this purpose, and the PhotoImage class needs to keep a reference to each image to avoid being garbage collected (which sometimes is a bit tricky).

Having said that, this is an example of how to draw single sprites with Tkinter (the spritesheet I have used for this example is this one, converted to a GIF file).

import Tkinter as tk

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.spritesheet = tk.PhotoImage(file="spritesheet.gif")
        self.num_sprintes = 4
        self.last_img = None
        self.images = [self.subimage(32*i, 0, 32*(i+1), 48) for i in range(self.num_sprintes)]
        self.canvas = tk.Canvas(self, width=100, height=100)
        self.canvas.pack()
        self.updateimage(0)

    def subimage(self, l, t, r, b):
        print(l,t,r,b)
        dst = tk.PhotoImage()
        dst.tk.call(dst, 'copy', self.spritesheet, '-from', l, t, r, b, '-to', 0, 0)
        return dst

    def updateimage(self, sprite):
        self.canvas.delete(self.last_img)
        self.last_img = self.canvas.create_image(16, 24, image=self.images[sprite])
        self.after(100, self.updateimage, (sprite+1) % self.num_sprintes)

app = App()
app.mainloop()
like image 167
A. Rodas Avatar answered Sep 19 '22 22:09

A. Rodas