问题
how can I set the z-index of tkinter canvas elements (circle, rectangle) on initial startup of the canvas? Or can I set a z-index directly when drawing e.g. a circle? Unfortunately I could not do much with canvas.tag_lower("tag_name")
. I thought this command moves all elements of a tag one level back - is that so?
class CanvasGui(tk.Canvas):
def __init__(self, master):
super().__init__(master, bg="#FFF", highlightthickness=0, borderwidth=0)
self.pack(fill="both", expand=True)
self.setCanvasLayers()
def setCanvasLayers(self):
self.tag_lower("highlightGridPoint")
self.tag_lower("grid")
In my opinion, the elements with the tag "highlightGridPoint" should now be in the farthest background and the elements with the tag "grid" in the foreground. But if I run the program, it's not so...
回答1:
You can't set the ordering of a tag until after the tag has been created. Your code raises and lowers tags that don't yet exist.
You can see this by noticing the difference in behavior between this code:
canvas.setCanvasLayers()
canvas.create_rectangle(10,10,50,50, fill="red", tags=("red",))
canvas.create_rectangle(20,20,60,60, fill="green", tags=("green",))
... and this code:
canvas.create_rectangle(10,10,50,50, fill="red", tags=("red",))
canvas.create_rectangle(20,20,60,60, fill="green", tags=("green",))
canvas.setCanvasLayers()
来源:https://stackoverflow.com/questions/60872650/how-do-i-set-the-z-index-of-an-python-tkinter-canvas-element