Problems with multiple Tkinter buttons

Question:

I was working on I just couldn’t get to work, I’ve written an example that I think displays the issue:

from tkinter import *

listing = [1, 2, 3, 4]

def PressedButton(listing):
    print(listing)

global root
root = Tk()
ListButton = []
for i in range(0, len(listing)):
    ListButton.append(Button(root, text= listing[i], command = lambda: 
PressedButton(listing[i])))
    ListButton[i].grid(row = i)

When I run this I always have the number 4 printed no matter what button I select, but all the buttons do have their correct respective number on them.

Thanks a lot for any help you guys could provide.

Asked By: DorMousePrd

||

Answers:

Well, there are many things related to bad programming practices within your code, and surely you have to read more about lambda expressions, so for the moment all what I can do is to provide you a solution to make your code work.

Change this:

... command = lambda: PressedButton(listing[i]) ...

to

... command = lambda i=i: PressedButton(listing[i]) ...
Answered By: Billal Begueradj
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.