#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    43
    Rep Power
    1

    [Python 2.7 + Tkinter] Add Button Array GUI not Works..., Error Found!


    Hey Python Programmers and GUI Developers...

    I try to create an test GUI, with means you can add an serie buttons if you get an number range
    typed in an entry.... but if i run my script.... i get an error found...


    So, this is my script, writting in python 2.7, on an older windows system:
    Code:
    from Tkinter import *
    
    def main():
        
        root = Tk()
        root.geometry("640x480")
        root.title("Button Array")
    
        can_add = True
    
        if can_add == True:
            
            a.config(command = AddArray)
            
        else:
            
            a.config(command = None)
    
    
    
    
        def AddArray():
    
            try:
                x = 1
                array = range(int(e.get()))
    
                for x in array:
                    b = Button(root, text = int(x), foreground = "white", background = "black", activebackground = "gray")
                    b.pack(fill = X, side = TOP)
                    x += 1
                can_add = False
                e.delete(0, END)
    
            except:
                can_add = True
                e.delete(0, END)
    
            
    
        def RemoveArray():
    
            try:
                b.destroy()
                can_add = True
    
            except:
                can_add = True
            
    
    
        e = Entry(root, background = "red")
        a = Button(root, text = "Add", foreground = "white", background = "red", activebackground = "orange")
        d = Button(root, text = "Delete", foreground = "white", background = "red", activebackground = "orange", command = RemoveArray)
    
        e.pack(fill = X, side = TOP)
        a.pack(fill = X, side = TOP)
        d.pack(fill = X, side = TOP)
            
        
        root.mainloop()
    
    
    
    if __name__ == "__main__":
        main()


    And this is my error:
    Traceback (most recent call last):
    File "C:/Documents and Settings/Eigenaar/Bureaublad/jamie/Python/Python Tkinter/Tkinter Button Array.py", line 66, in <module>
    main()
    File "C:/Documents and Settings/Eigenaar/Bureaublad/jamie/Python/Python Tkinter/Tkinter Button Array.py", line 13, in main
    a.config(command = AddArray)
    UnboundLocalError: local variable 'a' referenced before assignment

    The means of my test GUI is thad you can enter an number of buttons thad you want added,
    click at the "Add" Button and than must be to cant_added... so than press the "Delete" Button and
    than all buttons must be destroyed, just you can add an new number of buttons again... etc.

    But i get problems with my GUI, thad i used to play with Tkinter...

    Can anyone correct my code, pleace.... just i can experiment with it ?...
    Thanks for help, Jamie.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    664
    Rep Power
    39
    UnboundLocalError: local variable 'a' referenced before assignment
    This error occurs because you reference the variable a at the top of the program but don't create it until the bottom of the program. There are other problems as well. You use a for loop to create more buttons, but each button's ID is assigned to the variable b, which means that b contains the ID to the last button created only. This also means that you can only delete that last button created, but you can't even do that because you create b as a local variable under the AddArray function, i.e. you have b=, and so b will be garbage collected when the function exits. The following program uses a list to store the IDs of the buttons. Lists are mutable, meaning that a list declared in the global scope can be modified in a function. Also, I fixed your indentation, removed the main() function, which is used by some teachers/tutorials to teach about functions but rarely used beyond the beginner level, and changed the variable names to conform to the Python Style Guide, i.e. functions are lower case with underscores, and variables, from meaningless single letters to something that describes what they do.
    Code:
    """ Since I don't know what this program is supposed to do, beyond 
    adding and deleting buttons, that is all that this example does
    """
    from Tkinter import *
    
    
    def add_button():
            print "add button"
    
            try:
    ##            x = 1  ## local variable & so will be garbage collected
                num_buttons = range(int(e.get()))
    
                for x in num_buttons:
                    b = Button(root, text = int(x), foreground = "white", background = "black", activebackgro
                    b.pack(fill = X, side = TOP)
                    add_btn_ids.append(b)
    ##                x += 1
    ##            can_add = False  ## local variable & so will be garbage collected
    ##            e.delete(0, END)
    
            except:
    ##            can_add = True
                print "exception"
            e.delete(0, END)
    
    def remove_buttons():
            print "remove"
    
            try:
                ## deletes last button created
                last_btn_created=add_btn_ids[-1]
                last_btn_created.destroy()
                ## remove deleted button from list
                del add_btn_ids[-1]
    ##            can_add = True
    
            except:
    ##            can_add = True
                print "remove_buttons error"
                import traceback
                traceback.print_exc()
                raise
    
    if __name__ == "__main__":
        root = Tk()
        root.geometry("640x480")
        root.title("Button Array")
    
        add_btn_ids=[]
        e = Entry(root, background = "lightblue")
        e.focus_set()
    
        add_btn = Button(root, text = "Add", foreground = "white",
                         background = "red", activebackground = "orange")
    
        del_btn = Button(root, text = "Delete", foreground = "white",
                         background = "red", activebackground = "orange",
                         command = remove_buttons)
    
        e.pack(fill = X, side = TOP)
        add_btn.pack(fill = X, side = TOP)
        del_btn.pack(fill = X, side = TOP)
    
    ##    can_add = True
    
    ##    if can_add == True:  ## you just set it to True so the line is redundant
        add_btn.config(command = add_button)
    ##    else:
    ##        a.config(command = None)  ## you just set it to True so this line will never be reached
    
        root.mainloop()
    Last edited by dwblas; March 29th, 2018 at 12:51 PM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    43
    Rep Power
    1
    Originally Posted by dwblas
    This error occurs because you reference the variable a at the top of the program but don't create it until the bottom of the program. There are other problems as well. You use a for loop to create more buttons, but each button's ID is assigned to the variable b, which means that b contains the ID to the last button created only. This also means that you can only delete that last button created, but you can't even do that because you create b as a local variable under the AddArray function, i.e. you have b=, and so b will be garbage collected when the function exits. The following program uses a list to store the IDs of the buttons. Lists are mutable, meaning that a list declared in the global scope can be modified in a function. Also, I fixed your indentation, removed the main() function, which is used by some teachers/tutorials to teach about functions but rarely used beyond the beginner level, and changed the variable names to conform to the Python Style Guide, i.e. functions are lower case with underscores, and variables, from meaningless single letters to something that describes what they do.
    Code:
    """ Since I don't know what this program is supposed to do, beyond 
    adding and deleting buttons, that is all that this example does
    """
    from Tkinter import *
    
    
    def add_button():
            print "add button"
    
            try:
    ##            x = 1  ## local variable & so will be garbage collected
                num_buttons = range(int(e.get()))
    
                for x in num_buttons:
                    b = Button(root, text = int(x), foreground = "white", background = "black", activebackgro
                    b.pack(fill = X, side = TOP)
                    add_btn_ids.append(b)
    ##                x += 1
    ##            can_add = False  ## local variable & so will be garbage collected
    ##            e.delete(0, END)
    
            except:
    ##            can_add = True
                print "exception"
            e.delete(0, END)
    
    def remove_buttons():
            print "remove"
    
            try:
                ## deletes last button created
                last_btn_created=add_btn_ids[-1]
                last_btn_created.destroy()
                ## remove deleted button from list
                del add_btn_ids[-1]
    ##            can_add = True
    
            except:
    ##            can_add = True
                print "remove_buttons error"
                import traceback
                traceback.print_exc()
                raise
    
    if __name__ == "__main__":
        root = Tk()
        root.geometry("640x480")
        root.title("Button Array")
    
        add_btn_ids=[]
        e = Entry(root, background = "lightblue")
        e.focus_set()
    
        add_btn = Button(root, text = "Add", foreground = "white",
                         background = "red", activebackground = "orange")
    
        del_btn = Button(root, text = "Delete", foreground = "white",
                         background = "red", activebackground = "orange",
                         command = remove_buttons)
    
        e.pack(fill = X, side = TOP)
        add_btn.pack(fill = X, side = TOP)
        del_btn.pack(fill = X, side = TOP)
    
    ##    can_add = True
    
    ##    if can_add == True:  ## you just set it to True so the line is redundant
        add_btn.config(command = add_button)
    ##    else:
    ##        a.config(command = None)  ## you just set it to True so this line will never be reached
    
        root.mainloop()

    Sorry.... but your script they you get correcting for my don't will run....
    If i run your script, i get an error message (not an python error, but an message error with an red icon)....

    For more information, run your script and you can hopefully see whats wrong with it...
    Pleace can you figure out how i can fix this message error (and i means not an python error
    like TCLError, ValueError..., etc... but an normally windows message error is comming if
    i run your corrected script)...

    Thanks for help, Jamie.
  6. #4
  7. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,947
    Rep Power
    509
    What environment do you use that you see "red icon" instead of "syntax error"?
    On the line before the syntax error you'll certainly see unbalanced parentheses. The statement was clipped for whatever reason.

    Finish it with activebackground='blue') so the full line reads
    Code:
                    b = Button(root, text = int(x), foreground = "white", background = "black", activebackground='blue')
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    664
    Rep Power
    39
    A good reason why we don't let lines get longer than 70+ characters. The OP should be happy that you answered this as I would be more inclined to say "Now is the time to start learning to debug code".

IMN logo majestic logo threadwatch logo seochat tools logo