CREATION OF VARIABLE USING COUNT VARIABLE

Asked 2 years ago, Updated 2 years ago, 100 views

In tkinter, when creating 18 figures, I would like to create variables that accompany objects for management purposes, objects 0 to 17.
Therefore, we thought about using the count variable i to assign variables together when creating objects.

for range(0,17):
 "object" i=canvas.create_rectangle: ...

I tried to create a variable in the form of , but it was not…
I wondered if I could use regular expressions, but I couldn't think of them.

If anyone knows how to achieve this, I would appreciate it if you could let me know.
If I'm trying to do something that's not feasible in the first place, I'm going to give up this approach and create variables one line at a time, object1=..., object2=...

python tkinter

2022-09-29 21:20

2 Answers

That's too bad. If you use Python's "List," you'll see the following:Try running it in your environment, objects is the list.

 objects=[]

for i in range(18):
  objects.append("element" + str(i))

print(objects)

append is the method for adding elements to an array.You should be able to achieve what you want by making the argument a Tkinter object.

Note: List Type (list) - Embedded—Python 3.10.4 Documentation


2022-09-29 21:20

You can embed the value of the count variable in the code by using the exec command.

for i in range(0,17):
  exec("object{}=canvas.create_rectangle...".format(i))

exec and format are described as follows:

  • exec executes the string given as an argument as Python code
  • format substitutes the argument (this time the value of i) for the {} position.

Now you should be able to create variables from object0 to object17.


2022-09-29 21:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.