I have searched deeply for a solution to this problem, but, being new to Python and tkinter, it is difficult to find solutions to problems in a language you are largely unfamiliar with. I hope this is not a repeat question.
Suppose I create a series of buttons in tkinter, each of which will sequentially display a letter of the alphabet, defined as such:
from string import ascii_uppercase as alphabet
from tkinter import Button
blockLetterButtons = []
for i in range(0,26):
blockLetterButtons.append(Button(competitorSelectionFrame,
text=alphabet[i], command=some_function(alphabet[i])))
Somewhere below this in the for
loop is a .grid(...)
for all of these.
The function that is being referenced in the command
attribute is as the following:
def some_function(letter):
print(letter)
So I recognize two problems with my code:
- The function in the
command
attribute is executing immediately upon running the code, because I am specifying a function call rather than a function name. - Even if that was the proper way to call the function with a parameter, using
alphabet[i]
wouldn't work, because it would pass whatever the value ofi
is upon click, and not whateveri
was upon execution of thefor
loop.
So my questions are the following:
- How can I specify a function in the
command
attribute and pass to that function with a parameter? - How can I specify that parameter to be the letter of the alphabet specific to that button, without defining a button explicitly for every letter?
I am fairly certain I could use a list comprehension to solve the second problem, perhaps a dictionary with the key equal to the letter and the value equal to the button, but then I still wouldn't know how to get the key value from the button on its own.