Tkinter Canvas moves an item to the top level

I have a Tkinter Canvas widget (Python 2.7, not 3), and I have different objects on this canvas. If I create a new element that overlaps the old element, it will be in front. How can I move an old element before a newly created or even before all other elements on the canvas?

Code example:

from Tkinter import *
root = Tk()
canvas = Canvas(root,width=200,height=200,bg="white")
canvas.grid()
firstRect = canvas.create_rectangle(0,0,10,10,fill="red")
secondRect = canvas.create_rectangle(5,5,15,15,fill="blue")

now I want firstRect to be in front of secondRect.

+5
source share
2 answers

Use the methods tag_lower()and tag_raise()for the object Canvas:

canvas.tag_raise(firstRect)

Or:

canvas.tag_lower(secondRect)
+8
source

If you have several elements on the canvas and you don’t know which one will overlap, then do it.

# find the objects that overlap with the newly created one
# x1, y1, x2, y2 are the coordinates of the rectangle

overlappers = canvas.find_overlapping(x1, y1, x2, y2)

for object in overlappers:
    canvas.tag_raise(object)
0
source

All Articles