Python 创建后可以更改 Canvas 对象的属性吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12991717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you change the attributes of a Canvas object after creation?
提问by Brad Rice
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.
我正在尝试模拟一个美国交通灯,矩形上有 3 个圆圈,全部绘制在一组画布上。模拟应该通过按以下顺序每 2 秒更改显示的灯光来镜像“动画”:绿色 > 黄色 > 红色 > 绿色,等等。
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.
我能想到的唯一方法是使用 canvas.move()、canvas.after()、canvas.update() 模式移动一个填充的椭圆形对象,一次叠加一个未填充的圆圈。我已经掌握了以正确的速度和正确的顺序移动一个圆圈的逻辑。问题是,我只是实例化了一个充满“绿色”的圆圈,但我无法使用这种方法将其更改为“黄色”或“红色”。必须每 2 秒使用 canvas.delete("filled") 并在一个新的地方用不同的填充重新绘制它似乎很愚蠢,因为对于这样一个简单的程序来说,这有很多事情要做。
Question 1: Is there a way I can just alter the filloption for my filled Canvas object at will, using some method or other means?
问题 1:有没有办法可以fill使用某种方法或其他方式随意更改已填充的 Canvas 对象的选项?
Question 2: Am I approaching this scenario incorrectly? Is there a better way to simulate this?
问题 2:我是否错误地处理了这种情况?有没有更好的方法来模拟这个?
采纳答案by Junuxx
Yes you should be able to change settings of the canvas with config.
是的,您应该可以使用config.
Likewise, use itemconfigto change items on the canvas. This does require that you save a handle to the item or tag them.
同样,用于itemconfig更改画布上的项目。这确实需要您保存项目的句柄或标记它们。
Example from tkinterbook:
来自 tkinterbook 的示例:
i = w.create_line(xy, fill="red")
w.coords(i, new_xy) # change coordinates
w.itemconfig(i, fill="blue") # change color

