Using sprites in Tkinter

I am writing a GUI in Python Tkinter and I cannot find how to use the canvas canvas method to draw only one sprite from a sprite. Thanks in advance to everyone who can tell me what I need to do for this!

+4
source share
2 answers

First of all, I highly recommend that you use Pygame, since it has a specific module for this purpose, and the PhotoImage class must keep a link to each image to avoid garbage collection (which is sometimes a bit complicated).

Having said that, this is an example of how to draw single sprites using Tkinter (the spritesheet I 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() 
+3
source

You have several options:

Tkinter supports only 3 file formats: GIF, PGM and PPM. You will need to either convert the files to .GIF, or upload them, or you can use the Python Imaging Library (PIL) and its tkinter extension to use the PNG image.

You can download the PIL package here: http://www.pythonware.com/products/pil/

Alternatively, as mentioned above, PyGame is better integrated into image support and may be easier to use.

Good luck

0
source

Source: https://habr.com/ru/post/1481096/


All Articles