Jam
Jam

Reputation: 584

Tkinter image rendering is slow. How should I improve it?

I have an engine set up and the required GUI library I must use (and only non-builtin library I'm allowed to use) is tkinter. I'm not very experienced in TK though, and I'd like help improving my rendering performance. The way I implemented rendering is more or less as follows:

# assign png as PhotoImage
Resources.register(PhotoImage, '...circle-alpha.png')

# init window and canvas
root = Tk()
root.geometry = "600x1000"

canvas = Canvas(root, width=600, height=1000)
canvas.pack()

# using root.after I call this function every ~33ms
def main_loop():
  canvas.delete(ALL)
  Camera.main_camera.render()

# camera.render eventually calls this:
# sprite.image references the prviously-mentioned image
def render(self, camera):
  canvas.create_image(self.pos.x, self.pos.y, image=self.sprite.image

So what this is doing is: for every object that has a renderer attatched, the main camera checks if it can see the object. If so, the object creates its image on the canvas. Once this process is complete, the canvas is cleared and the process is repeated

problem: this process can take more than the allotted 33ms to move 1 128x128 png across the screen. What are some ways I can improve my rendering method?

Upvotes: 3

Views: 1295

Answers (1)

You shouldn't recreate the canvas image every time you want to move it. Instead, create the image just once and save it to a variable: my_image = canvas.create_image(self.pos.x, self.pos.y, image=self.sprite.image).

When you call the create_image method, it returns an integer value that the canvas associates with the image, so you can use this later on in the code to do things to the image, like moving it: canvas.moveto(my_image, self.pos.x, self.pos.y). So the render() function would look like this:

def render(self, camera):
    canvas.moveto(my_image, self.pos.x, self.pos.y)

Upvotes: 3

Related Questions