I've run into a snag with my first attempt at using tkinter. I need to create a lot of buttons, so to make the code look a bit cleaner I used a for loop and dynamic variable names to create each button. The problem with this is that when each button is created, the btnClick(x) is run for that button. So I have PING! 1, PING! 2, ... in my terminal. On top of that, the buttons are unresponsive after creating the window (clicking them gives no response).
Is there a way to use the for loop / dynamic variables and have the buttons work, or is the only way to write it out for every button?
from tkinter import *
window = Tk()
btns = {}
btnNames = ["Description", "Tags", "Display", "Armor",
"Hit Points", "Damage", "Speed", "Ability Scores",
"Saving Throws", "Skills", "Vulnerabilities", "Resistances",
"Immunities (Damage)", "Immunities (Conditions)", "Senses", "Languages",
"Traits", "Actions", "Reactions", "Paragon Actions",
"Ledgendary Actions", "Lair Actions", "Notes"]
def StartWindow():
# set Basics
window.title("Monster Maker")
window.geometry('900x600')
# Set Icon
window.iconbitmap("Sources/Icon.ico")
MonsterMaker()
# Run window
window.mainloop()
def MonsterMaker():
for x in range(23):
name = "btn" + str(x)
btns[name] = Button(window, text=btnNames[x], command=btnClick(x), width=20, height=1)
btns[name].grid(column=0, row=x)
def btnClick(index):
print("PING! " + str(index))
if __name__ == "__main__":
StartWindow()```