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

时间:2016-02-12 15:06:12

标签: python tkinter tkinter-canvas

我在画布上创建了两个重叠按钮,使用tkinter和python 3.4:

button1 is below button2

现在我想把button1带到前面(你现在看不到的按钮,因为它在按钮2下面)

self.canvas.lift(self.button1)

但由于某种原因,这不起作用。什么都没发生。降低button2也无效。你能告诉我为什么吗?

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()

1 个答案:

答案 0 :(得分:6)

不是在画布上调用lift(),而是需要直接在窗口小部件实例上调用它:

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

仅适用于通过画布上的窗口显示的小部件。

如果您要绘制线条或矩形等对象,则可以像以前一样在画布实例上使用lift()tag_raise()