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:
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?
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?
Comment