Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you change the attributes of a Canvas object after creation?

I'm trying to simulate an American traffic light, with 3 circles on a rectangle, all drawn on a set Canvas. The simulation is supposed to mirror "animation" by changing which light is displayed every 2 seconds in the following order: green > yellow > red > green, etc forever.

The only way I can think of to do this is by using a canvas.move(), canvas.after(), canvas.update() pattern to move a filled oval object to superimpose one unfilled circle at a time. I've gotten the logic down to move a circle at the proper speed and in the correct order. The thing is, I just instantiate a circle filled with "green", but I can't change it to be "yellow" or "red" using this method. It seems silly to have to canvas.delete("filled") and redraw it in a new place with a different fill every 2 seconds, because that's a lot to do for such a simple program.

Question 1: Is there a way I can just alter the fill option for my filled Canvas object at will, using some method or other means?

Question 2: Am I approaching this scenario incorrectly? Is there a better way to simulate this?

like image 909
Brad Rice Avatar asked Oct 20 '12 19:10

Brad Rice


People also ask

How do I change the size of a canvas in Python?

Python Tkinter Canvas size can be decided by providing height and width. Height is the vertical position of canvas on the parent window. Width is the horizontal position of the canvas on the parent window. Change in the height & width will change the size of the canvas.

How do I use canvas in Itemconfig?

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.

What is a Tk canvas?

A tkinter canvas can be used to draw in a window. Use this widget to draw graphs or plots. You can even use it to create graphical editors. You can draw several widgets in the canvas: arc bitmap, images, lines, rectangles, text, pieslices, ovals, polygons, ovals, polygons, and rectangles.


1 Answers

Yes you should be able to change settings of the canvas with config().

Likewise, use itemconfig() to change items on the canvas. This does require that you save a handle to the item or tag them.

Example based on tkinterbook:

item = canvas.create_line(xy, fill="red")

canvas.coords(item, new_xy) # change coordinates
canvas.itemconfig(item, fill="blue") # change color
like image 72
Junuxx Avatar answered Oct 05 '22 13:10

Junuxx