简体   繁体   中英

How can I bring a Canvas to front?

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?

You can use the following functions -

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

canvas.tag_lower(canvas_layer4) -> For pushing back

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM