简体   繁体   English

使用循环创建Tkinter画布对象时对其进行修改

[英]Modifying a tkinter canvas object when creating it with a loop

I am trying to change the colors of a few canvas objects based on a 24 bit value that is randomly modified. 我试图根据随机修改的24位值更改一些画布对象的颜色。

class Person:
def __init__(self, canvas, pts, i):
    canvas.create_oval(pts[i][0]+355, pts[i][1]+155,
                         pts[i][0]+355 + GUI.people_size_var.get(), pts[i][1] + 155 + GUI.people_size_var.get(),
                         fill="yellow", outline="black", width=2, tags="people")

When this class is called, I create an oval inside a canvas. 调用此类时,我在画布内创建了一个椭圆形。 What I want to do is to be able to access every single one of those ovals separately, in order to modify their color. 我想要做的是能够分别访问这些椭圆中的每个椭圆,以修改其颜色。 Is there any way of doing that? 有什么办法吗? I thought of tagging them with the (i) integer, which is the (i) from a loop, but I'm not sure if that would work. 我曾想过用(i)整数(即循环中的(i))标记它们,但我不确定是否可行。 Also, if I want to modify those with a function that belongs to another class, can I do so by just using the tags, or do I have to call something from the Person class? 另外,如果我想使用属于另一个类的函数来修改它们,是否可以仅使用标签来进行修改,还是必须从Person类中调用某些东西?

Thank you. 谢谢。

When you create an item on the canvas, it returns a unique id. 当您在画布上创建一个项目时,它会返回一个唯一的ID。 You can save that id and reference it later: 您可以保存该ID并在以后引用它:

class Person:
    def __init__(self, canvas, pts, i):
        self.canvas = canvas
        self.oval_id = self.canvas.create_oval(...)

    def change_color(self):
        self.canvas.itemconfigure(self.oval_id, ...)

Also, if I want to modify those with a function that belongs to another class, can I do so by just using the tags, or do I have to call something from the Person class? 另外,如果我想使用属于另一个类的函数来修改它们,是否可以仅使用标签来进行修改,还是必须从Person类中调用某些东西?

The best thing is to call something from the Person class, IMO. 最好的办法是从Person类IMO中调用某些东西。 The reason being, the other parts of your program shouldn't depend on how the Person class is implemented. 原因是,程序的其他部分不应取决于Person类的实现方式。

Consider the case where you want to change from an oval to a rectangle, or to an image or some other widget. 考虑要从椭圆形更改为矩形,或将图像更改为其他控件的情况。 By making other parts of your code call methods on the object, you won't have to modify any of your code except for the Person class. 通过在对象上进行代码调用方法的其他部分,您无需修改​​任何代码(Person类除外)。

If the rest of your program depends on the fact that a Person creates a single canvas object, you've created a tight coupling. 如果程序的其余部分取决于Person创建单个画布对象这一事实,则说明您已经创建了紧密耦合。 This means you have to change a lot of code if you want to change the implementation of a single class. 这意味着如果要更改单个类的实现,则必须更改很多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM