1

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:

  • self.oval_id1 = self.canvas.create_oval(40,40,60,60)

  • self.oval_id2 = self.canvas.create_oval(60,40,80,60)...etc

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()
2
  • 2
    Just build a string out of your loop-index (or in some more crazy setups; your question is broad here; use uuid's). Commented Jan 6, 2018 at 12:59
  • Store the oval identifiers in a list or dictionary. Commented Jan 8, 2018 at 3:43

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or even a dictionary if you want to give things descriptive names
0

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

1 Comment

This is too complicated, when you can simply store the identifiers in a list or dictionary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.