How do I set the z index of an Python tkinter canvas element?

大憨熊 提交于 2020-05-17 03:11:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!