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.
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]) ...
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.
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]) ...