Reputation: 85
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()
Upvotes: 1
Views: 50
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
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