0

I need to generate buttons randomly from A-Z and that will execute respective python files using os.system('A.py') when clicked. I used random_alphabets = random.sample(range(1, 26), 5) to generate the random numbers and executed a for loop to add the buttons dynamically like:

for i in self.random_alphabets:
    a_button = tk.Button(self,text=chr(i+64),command=lambda: os.system(str(chr(i+64))+".py"))
    a_button.grid(row=0,column=i)

When I run this GUI, only the last randomly generated file gets executed. Suppose the randomly generated alphabets are ['U', 'S', 'E', 'Q', 'O'], then when I click on any button, only the "O.py" gets executed.

How to tackle this issue?

Tejas
  • 224
  • 1
  • 10

1 Answers1

0

You need to capture the current value, as the lambda closure will always only close over names, not their values. So a simple lambda i=i: ... should do the trick.

deets
  • 6,285
  • 29
  • 28
  • Yes it worked. But on a second note, the buttons are not loaded in the proper order. That is if the order is ['U', 'S', 'E', 'Q', 'O'], then the buttons in the GUI are not being added in the same order. How to make them in the same order? – Tejas Apr 30 '18 at 14:47
  • That is a different question - it’s about the layout. And without a fully reproducible example it’s not possible to answer. – deets Apr 30 '18 at 18:28