Guido
Guido

Reputation: 688

How to create a tkinter background image?

I need to draw a ball moving on a canvas with a background (floor map) image. I succeded to load the image, and to draw the ball moving, but the canvas ball is not placed on top of the background.

import Tkinter as tk
import random
import time
from PIL import ImageTk, Image

root = tk.Tk()
root.resizable(width=False, height=False)
root.wm_attributes("-topmost", 1)
path = 'C:\xx\Pictures\xxx.jpg'
img = Image.open(path)
photo = ImageTk.PhotoImage(img)

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 1, 1)
        self.canvas.after(50, self.draw)


canvas = tk.Canvas(root,  bd=0, highlightthickness=0)
canvas.pack()
background_label = tk.Label(root, image = photo)
background_label.place(x=0, y=0, relwidth=1.0, relheight=1.0, anchor="center")
background_label.pack( )

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

Upvotes: 2

Views: 1781

Answers (1)

tobias_k
tobias_k

Reputation: 82889

You load the image in a label that's placed below the canvas you draw the ball in. You have to load the image in the same canvas.

Replace this

background_label = tk.Label(root, image = photo)
background_label.place(x=0, y=0, relwidth=1.0, relheight=1.0, anchor="center")
background_label.pack( )

with this:

canvas.create_image(0, 0, image=photo)

Make sure to create the image before you create the ball to get the z-ordering right.

Upvotes: 3

Related Questions