Tkinter button command question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tsunexus
    New Member
    • Apr 2010
    • 2

    Tkinter button command question

    What i am doing is creating a set of buttons from strings read from a file. When clicked, the button then adds the string to a listbox using a function i made called "additem(item)" .

    code similar to this:
    Code:
    #global variables
    root = Tk()
    myframe = Frame(...)
    mylist = Listbox(....)
    myfile = open("myfile.txt", "r")
    
    def additem(item):
         mylist.insert(END, item)
    
    def makebuttons():
         MyButtons = []
         line = myfile.readline()
         i  = 0
        while line != "":
               mystring = line.rstrip("\n")
               MyButtons.append(Button(myframe, text=mystring, command = lambda: additem(mystring))
               MyButtons[i].pack()
               line = myfile.readline()
               i+=1
    
    makebuttons()
    myframe.pack()
    myfile.close()
    root.mainloop()

    but the problem is, when clicked it always adds the last item to the list box. I m aware that it is because it is using what is stored in the variable "mystring" at the time the button is being pressed, but is there any way to make it use the variable contents from when its created. Ive also tried making item a global variable and not passing mystring and not using lambda, but it still does the same thing. Any Suggestions?
    Last edited by Tsunexus; Apr 25 '10, 07:48 PM. Reason: forgot something
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The following is untested, but should work:
    Code:
    def makebuttons():
        MyButtons = []
        for i, line in enumerate(myfile):
            mystring = line.rstrip("\n")
            def handler(item=mystring):
                additem(item)
            MyButtons.append(Button(myframe, text=mystring, command=handler)
            MyButtons[i].pack()

    Comment

    • Tsunexus
      New Member
      • Apr 2010
      • 2

      #3
      Works like a charm, thanks a million... My biggest problem was that i understood exactly why it wasn't working, but would never have thought to take your approach.

      Comment

      Working...