Python & tkinter:重叠按钮上的 canvas.lift 和 canvas.lower 不起作用
Python & tkinter: canvas.lift and canvas.lower on overlapping buttons does not work
我使用 tkinter 和 python 3.4 在 canvas 上创建了两个重叠按钮:
现在我想把 button1 放在前面(你现在看不到的按钮,因为它在 button2 下面)
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()
无需在 canvas 上调用 lift()
,您需要直接在小部件实例上调用它:
def click_on_canvas(self, event):
print("lifting", self.button1)
self.button1.lift()
self.button2.lower() # Not necessary to both lift and lower
这仅适用于通过 canvas 上的 window 显示的小部件。
如果您要绘制线条或矩形等对象,您可以像以前一样在 canvas 实例上使用 lift()
或 tag_raise()
。
我使用 tkinter 和 python 3.4 在 canvas 上创建了两个重叠按钮:
现在我想把 button1 放在前面(你现在看不到的按钮,因为它在 button2 下面)
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()
无需在 canvas 上调用 lift()
,您需要直接在小部件实例上调用它:
def click_on_canvas(self, event):
print("lifting", self.button1)
self.button1.lift()
self.button2.lower() # Not necessary to both lift and lower
这仅适用于通过 canvas 上的 window 显示的小部件。
如果您要绘制线条或矩形等对象,您可以像以前一样在 canvas 实例上使用 lift()
或 tag_raise()
。