1

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

aless80
  • 3,122
  • 3
  • 34
  • 53
  • are you looking for a general purpose solution, or are you specifically wanting to solve the problem of a border getting obscured? For a simple layering mechanism see http://stackoverflow.com/a/9576938/7432 – Bryan Oakley Aug 31 '16 at 13:55
  • tag_raise worked from me. I am now aware of similar methods such as lift/lower. Your post is also interesting, thanks – aless80 Aug 31 '16 at 14:05

1 Answers1

1

Use tag_raise() method:

canvas.tag_raise(tile)
Kenly
  • 24,317
  • 7
  • 44
  • 60
  • Thank you, that worked. Now that you suggested tag_raise I see that my question might be a duplicate of this one: http://stackoverflow.com/questions/10959858/tkinter-canvas-move-item-to-top-level In my real case I have more images, foreground and background rectangles that had to stay below or on top of each other. I defined some tags and called tag_raise on the tags, eg: canvas.tag_raise("ontop") – aless80 Feb 28 '16 at 14:40