-1

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()```
Ivaldir
  • 185
  • 12
  • Does this answer your question? [why-is-button-parameter-command-executed-when-declared](https://stackoverflow.com/questions/5767228) – stovfl May 13 '20 at 10:49

1 Answers1

2

The problem is that you are calling the btnClick function on button creation, but you want to pass that function as an argument. Instead use lambdas:

btns[name] = Button(window, text=btnNames[x], command=lambda arg=x: btnClick(arg), width=20, height=1)

Hope that's helpful!

rizerphe
  • 1,340
  • 1
  • 14
  • 24