Jozko
Jozko

Reputation: 85

Making unique identifier in Python

I made a simple program with ten ovals. I will work with them later and I'll need to move ovals, so I need unique name for every oval. However, there is a lot of ovals so I don't want to make every oval on new line of code. I used loop, but then I am not able to make unique name for them. Like for example:

Is there any way to make such names in loop please?

import tkinter
class Main:
    def __init__(self):
        self.canvas = tkinter.Canvas(width=500, height=300)
        self.canvas.pack()
        x, y = 50, 50
        for i in range(10):
            self.canvas.create_oval(x-10,y-10,x+10,y+10)
            x += 30
main = Main()

Upvotes: 1

Views: 50

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148900

Even if tricks could allow you to achieve that, you do not want that. It you need it to be iterable, use an iterable container first, here a list.

class Main:
    def __init__(self):
        self.canvas = tkinter.Canvas(width=500, height=300)
        self.canvas.pack()
        self.oval_id = []
        x, y = 50, 50
        for i in range(10):
            self.oval_id.append(self.canvas.create_oval(x-10,y-10,x+10,y+10))
            x += 30

You can now use self.oval_id[i] to access the i-th oval

Upvotes: 2

Erez
Erez

Reputation: 1430

You probably want setattr:

So, something like:

class Main:
    def __init__(self):
        self.canvas = tkinter.Canvas(width=500, height=300)
        self.canvas.pack()
        x, y = 50, 50
        for i in range(10):
            oval = self.canvas.create_oval(x-10,y-10,x+10,y+10)
            setattr(self, 'oval_%d' % i, oval)
            x += 30

Upvotes: 0

Related Questions