简体   繁体   English

Python&tkinter:canvas.lift和canvas.lower重叠按钮不起作用

[英]Python & tkinter: canvas.lift and canvas.lower on overlapping buttons does not work

I created two overlapping buttons on a canvas, using tkinter and python 3.4: 我使用tkinter和python 3.4在画布上创建了两个重叠的按钮:

button1位于button2下方

Now I would like to bring button1 to the front (the button you cannot see right now, because it is under button2) 现在我想把button1带到前面(你现在看不到的按钮,因为它在按钮2下面)

self.canvas.lift(self.button1)

But for some reason this does not work. 但由于某种原因,这不起作用。 Just nothing happens. 什么都没发生。 Also lowering button2 has no effect. 降低button2也无效。 Can you tell me why? 你能告诉我为什么吗?

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(self, width=400, height=400, background="bisque")
        self.canvas.create_text(50,10, anchor="nw", text="Click to lift button1")
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.canvas.bind("<ButtonPress-1>", self.click_on_canvas)

        self.button1 = tk.Button(self.canvas, text="button1")        
        self.button2 = tk.Button(self.canvas, text="button2")

        x = 40
        self.canvas.create_window(x, x, window=self.button1)
        self.canvas.create_window(x+5, x+5, window=self.button2)



    def click_on_canvas(self, event):

        print("lifting", self.button1)
        self.canvas.lift(self.button1)
        self.canvas.lower(self.button2)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

Instead of calling lift() on the canvas, you need to call it on the widget instance directly: 您需要直接在窗口小部件实例上调用它,而不是在画布上调用lift()

def click_on_canvas(self, event):
    print("lifting", self.button1)
    self.button1.lift()
    self.button2.lower()   # Not necessary to both lift and lower

This is only true for widgets displayed via a window on your canvas. 这仅适用于通过画布上的窗口显示的窗口小部件。

If you were to draw objects such as lines or rectangles, you would use lift() or tag_raise() on the canvas instance as you were doing before. 如果要绘制线条或矩形等对象,则可以像以前一样在画布实例上使用lift()tag_raise()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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