[Python] Tkinter: Canvas item color change on state change

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    The Tkinter code below displays a root window containing a canvas and a blue rectangle. Clicking on the rectangle toggles its state between 'normal' and 'disabled'.

    I'd like to also toggle its color. I know how to do it using canvas.itemconfig(rect, fill='red') for example, by checking its state.

    However, given that fill and disabledfill were defined, I expected the color to change automatically when the state changes. This does not happen.

    Is it possible to achieve this color change simply by altering the state?"

    ps. the color changes as I expect clicking on the canvas but not on the rectangle.

    MWE

    import tkinter as tk

    # toggle rect state
    def toggle_rect(event):
    item = canvas.find_closest(event.x, event.y)

    current_state = canvas.itemcget(item, "state")
    print(f'current state: {current_state}')

    new_state = "disabled" if current_state == "normal" else "normal"

    canvas.itemconfig(item, state=new_state)
    print(f'new state: {canvas.itemcget(item, "state")}')

    root = tk.Tk()
    canvas = tk.Canvas(root, width=400, height=400, bg='white')
    canvas.pack()

    rect = canvas.create_rectangle(50, 50, 150, 150, fill='blue', disabledfill='red', state='normal')
    canvas.bind("<Button-1>", toggle_rect)

    root.mainloop()

    Continue reading...

Compartilhe esta Página