Home > Software engineering >  How to raise a canvas item above a canvas window item
How to raise a canvas item above a canvas window item

Time:10-25

There is a solution for raising canvas windows over other canvas windows: How do you change the stacking order of window items in a canvas? But I am not able to raise a not-canvas-window item (for example a canvas rectangle) above a canvas window item. How can I do this?

Here is an example code where I try to raise the rectangle above a canvas window (the example was copied from the link above and extended by a canvas rectangle):


root = tk.Tk()

canvas = tk.Canvas(root, bg="bisque")
canvas.pack(fill="both", expand=True)

def focus_win(event):
    event.widget.lift()

for n, color in enumerate(("black", "red", "orange", "green", "blue", "white")):
    win = tk.Frame(canvas, background=color, width=100, height=100)
    x = 50   n*20
    y = 50   n*20
    canvas.create_window(x, y, window=win)
    win.bind("<1>", focus_win)
rec = canvas.create_rectangle(x, y, x 100, y 100)
canvas.tag_raise(rec, "all")


root.mainloop()

CodePudding user response:

But I am not able to raise a not-canvas-window item (for example a canvas rectangle) above a canvas window item. How can I do this?

You can't. The documentation says:

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being “on top” of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the Tk raise command and lower command instead.

Or can you ?

I mean you always could have multiple canvases as window-items and draw what ever you want to in those canvases.

  • Related