Dynamic buttons with dynamic command executes only last command tkinter

Question:

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?

Asked By: Tejas

||

Answers:

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.

Answered By: deets
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.