0

I am currently trying to make a calculator and I want to create the buttons for numbers in a loop, rather than 10 different hard-coded variables.

I am now trying to take a previously loop-made series of variables (i.e. var0 to var9) and do something with it, but I am stuck at how to do that.

Here's my code for reference:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for num in range(0, 10):
    exec (f'var{num} = x[num]')
    for i in range(0, 10):
        exec (f'btn{i} = Button(calc, padx=16, bd=8, fg="black", font = ("Times New Roman", 18, "bold"), text = x[i], command = lambda:btnClick(x[i]))')
        

What I have in mind now is to do something like:

for j in range(0, 10):
     btn{j}.grid(row = , column = )

as a third for loop and I don't know how to do extract btn{j} part. Any ideas would be appreciated!

Apologies if the code is cringeworthy, I am a beginner

Hopfield
  • 21
  • 2
  • 3
    Use a `dict` instead of multiple similar variable names. `var = {num: x[num] for num in range(10)]}` or `var = dict(zip(range(10), x))`. – chepner Jan 11 '21 at 18:32
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – buran Jan 11 '21 at 18:39

0 Answers0