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!
-
2There is an example of handling spritesheets @ pygame: http://www.pygame.org/wiki/Spritesheet . It shouldn't be much effort to use it together with Canvas.create_image . – Marcin Kowalczyk May 16 '13 at 12:32
2 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()

- 20,171
- 8
- 62
- 72
-
This approach is likely to eventually have performance problems because it keeps deleting and creating new canvas image objects. See this [answer](https://stackoverflow.com/a/37766721/355230) for an explanation. – martineau Apr 22 '19 at 16:36
-
https://stackoverflow.com/questions/59584567/tkinter-tclerror-coordinates-for-from-option-extend-outside-source-image I use your code example but i have some trouble. If you have a any suggest... – Nikola Lukic Jan 03 '20 at 19:54
You have a few options here:
Tkinter only supports 3 file formats: GIF, PGM, and PPM. You will either need to convert the files to .GIF then load them or you can use the Python Imaging Library (PIL) and its tkinter extensions to use a PNG image.
You can download the PIL package here: http://www.pythonware.com/products/pil/
Alternatively, as mentioned above, PyGame has better built in support for images and may be easier to use.
Good luck!

- 902
- 9
- 28