aless80
aless80

Reputation: 3332

How to keep a Tkinter widget on top of the others

I have some code that moves images left and right but I do not want them to appear on top of the right border, which I draw as a rectangle. What are the options in Tkinter to keep a widget (in my example a rectangle) on top of some other widgets (in my code a tile, which is an image)? I am drawing the rectangle and the image on one canvas.

I can image that using two canvas could do the trick, but are there any other options/settings? Thanks

import Tkinter as tk # for Python2
import PIL.Image, PIL.ImageTk

win = tk.Tk()
#Create a canvas
canvas = tk.Canvas(win, height = 500, width = 500)

#Create a rectangle on the right of the canvas
rect = canvas.create_rectangle(250, 0, 500, 250, width = 2, fill = "red")

#Create an image
SPRITE = PIL.Image.open("sprite.png")
tilePIL = SPRITE.resize((100, 100))
tilePI = PIL.ImageTk.PhotoImage(tilePIL)
tile = canvas.create_image(100, 100, image = tilePI, tags = "a tag")

#Place the canvas
canvas.grid(row = 1, column = 0, rowspan = 5)

#Move the tile to the right. 
#The tile will go on top of red rectangle. How to keep the rectangle on top of the tile?
canvas.coords(tile, (300, 100))
canvas.mainloop()

enter image description here

Upvotes: 1

Views: 4283

Answers (1)

Kenly
Kenly

Reputation: 26688

Use tag_raise() method:

canvas.tag_raise(tile)

Upvotes: 1

Related Questions