0

I'm trying to modify the background and the state of differents buttons in Tkinter, however my buttons are created in a function with exec() (that execute a program in str variable) :

def creationinterface():
    global letterstable #table with letters of alphabet
    text1='= Button(c1,text="'
    text2='",font=("Serif", 10),height="1",width="2",command= lambda : newletter("'
    text3='"))\nbtn'
    text4='.place('
    text5='anchor=NW)'
    x=5
    y=5


    for i in range(len(letterstable)-1):
        nexbtn="btn"+str(letterstable[i])+text+str(letterstable[i])+text1+letterstable[i]+txt3+str(letterstable[i])+txt2+"x="+str(x)+",y="+str(y)+","+text2
        exec(nexbtn) 

#exemple of nexbtn :
#btna= Button(c1,text="˽",font=("Serif", 12),height="1",width="16",command=lambda : newletter("a"))
#btna.place(x=57,y=83,anchor=NW)

my probleme is that I cant change buttons settings : NameError: name 'btna' is not defined, I think that the reason is that the button isn't setting in the code (I don't want to have 60 lines of buttons creation). Thanks for your help :)

  • 1
    Can you tell us why are you creating buttons with `exec()`? It is the most unadvisable way of doing that. – Saad Jun 27 '20 at 17:44
  • 2
    This is NOT a reasonable way to create buttons, not even close. Just create them in a loop, then store them in a dictionary or list. – jasonharper Jun 27 '20 at 17:45
  • You really should not use `exec` this way. It makes the code really hard to understand, modify, and test. Plus, it really provides absolutely no value over other possible solutions such as storing widgets in a dictionary. – Bryan Oakley Jun 27 '20 at 17:47
  • @jasonharper thank you, how can I create it in a loop without using exec? – artagon Jun 27 '20 at 18:01
  • See https://stackoverflow.com/a/49453736/7432 – Bryan Oakley Jun 27 '20 at 18:41

0 Answers0