How to reconfigure Tkinter canvas items?

TkinterGUI-ProgrammingPython

Using the Canvas widget, we can create text, images, graphics, and visual content to add to the Canvas widget. If you need to configure the Canvas item dynamically, then tkinter provides itemconfig(**options) method. You can use this method to configure the properties and attributes of the Canvas items. For example, if we create a line inside the Canvas widget, we can configure its color or width using itemconfig() method.

Example

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to delete the shape
def on_click():
   canvas.itemconfig(line, fill="green")

# Create a canvas widget
canvas = Canvas(win, width=500, height=300)
canvas.pack()

# Add a line in canvas widget
line = canvas.create_line(100, 200, 200, 35, fill="yellow", width=5)

# Create a button to delete the button
Button(win, text="Update the Color", command=on_click).pack()

win.mainloop()

Output

If you run the above code, it will display a window with a button and a line on the canvas.

Now, click the button to change the color of the canvas item.

raja
Published on 06-Aug-2021 06:43:30
Advertisements