简体   繁体   中英

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.

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. 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?

Thank you.

When you create an item on the canvas, it returns a unique id. You can save that id and reference it later:

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?

The best thing is to call something from the Person class, IMO. The reason being, the other parts of your program shouldn't depend on how the Person class is implemented.

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.

If the rest of your program depends on the fact that a Person creates a single canvas object, you've created a tight coupling. This means you have to change a lot of code if you want to change the implementation of a single class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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