Home > front end >  How can I bring a Canvas to front?
How can I bring a Canvas to front?

Time:12-10

I overlapped 5 Tk.Canvas objects and each will have different images. I want to bring each canvas to front of every other canvases to draw pictures in the most-front canvas.

class window_tk():
def __init__(self,main):
    self.main=main
    self.canvas_org = tk.Canvas(self.main, bg='white')
    self.canvas_layer1 = tk.Canvas(self.main, bg='red')
    self.canvas_layer2 = tk.Canvas(self.main, bg='green')
    self.canvas_layer3 = tk.Canvas(self.main, bg='blue')
    self.canvas_layer4 = tk.Canvas(self.main, bg='black')
    self.btn_load = tk.Button(self.main,text = "Load Image",command = self.load_ct)
    self.btn_layer1 = tk.Button(self.main,text = "Draw in L1",command = self.bring_1)
    self.btn_layer2 = tk.Button(self.main,text = "Draw in L2",command = self.bring_2)
    self.btn_layer3 = tk.Button(self.main,text = "Draw in L3",command = self.bring_3)
    self.btn_layer4 = tk.Button(self.main,text = "Draw in L4",command = self.bring_4)

def bring_1(self):
    self.canvas_layer1.place(x=50,y=00)

def bring_2(self):
    self.canvas_layer2.place(x=50, y=00)

def bring_3(self):
    self.canvas_layer3.place(x=50, y=00)

def bring_4(self):
    self.canvas_layer4.place(x=50, y=00)

I thought the canvas.place() function will bring the canvas front but it was not. Which function can I use ? Or should I unpack all other canvases ?

CodePudding user response:

Since Canvas has override the .tkraise() function, you need to call TCL command directly:

self.canvas.tk.call('raise', self.canvas._w)

CodePudding user response:

You can use the following functions -

canvas.tag_raise(canvas_layer4) -> For bringing to front

canvas.tag_lower(canvas_layer4) -> For pushing back

CodePudding user response:

Please see the answer given by acw1668. The lift function doesn't work for Canvas objects. His answer is correct.

All tkinter objects, Canvas included, support the following method:

w.lift(aboveThis=None) If the argument is None, the window containing w is moved to the top of the window stacking order. To move the window just above some Toplevel window w, pass w as an argument.

This gives you full control over which widget sits on top.

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

Now that I re-read that, I see that its language is slightly incorrect. "w" is any tkinter widget, "above_this" is another tkinter widget. The function places "w" above "above_this" in the stacking order.

CodePudding user response:

You can simply do this on the canvas element you want to bring to front:

canvas { 
    position: absolute;
    z-index: 100;
}

z-index is used to define the stack order of the elements! https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

  • Related