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

安稳与你 提交于 2019-11-30 04:55:28

问题


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?


回答1:


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 from tkinterbook:

i = w.create_line(xy, fill="red")

w.coords(i, new_xy) # change coordinates
w.itemconfig(i, fill="blue") # change color


来源:https://stackoverflow.com/questions/12991717/can-you-change-the-attributes-of-a-canvas-object-after-creation

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