编程语言
首页 > 编程语言> > Python&tkinter:canvas.lift和canvas.lower重叠按钮不起作用

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

作者:互联网

我使用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()

解决方法:

您需要直接在窗口小部件实例上调用它,而不是在画布上调用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().

标签:python,tkinter,tkinter-canvas
来源: https://codeday.me/bug/20190528/1167695.html