-1

I have made a text-file management system in Python3 using Tkinter and SQLite3. Every user's files are stored in a database. On the main screen when a user is logged in, a for-loop iterates over the file-names and creates a button for every file. Each button has to open up the file corresponding to its name.

The problem is, all the buttons open the file corresponding to the last button, instead of the file name corresponding to them.

To be more clear, here's my code:

for i in viewdata:
        doc=Button( mainframe, image=docimg, bd=0,cursor='hand1',  command=lambda: openexistingfile(str(i[0])))
        doc.place(x=cnt, y=70)
        doc.image=docimg
        Label(mainframe, text=str(i[0]), font='Times 12 italic', bg='white').place(x=cnt, y=130)
        cnt+=120
        print(str(i[0]))

Suppose a user has 3 files, sample1, sample2 and sample3. So here, viewdata = [(sample1, ), (sample2,), (sample3,)]. Now, three buttons would be created, each opening a file. However, all the buttons are opening sample3 for some reason.

The last print statement prints the file names correctly and in the correct format, it's only the Button command I'm having an issue with.

Any help would be appreciated. Thank you.

2 Answers2

0

You should be creating 3 different Button objects.
Currently, your code is overriding the previous object assignment with the latest one in doc name.

ycx
  • 3,155
  • 3
  • 14
  • 26
  • But a user could have any number of files. How do I know how many objects I have to make? – Soumya Mukhija Dec 15 '18 at 08:02
  • You can create a dictionary where keys are strings such as doc1, doc2, etc and use the iterator to input in the number. Your values will be the Button objects and you will be able to call each object via the key of the dictionary. I’ll edit and post sample code in the answer in a while. – ycx Dec 15 '18 at 08:33
  • I tried that, but it doesn't work. – Soumya Mukhija Dec 16 '18 at 15:46
  • Have you tried the link provided in https://stackoverflow.com/questions/39174661/tkinter-button-commands-in-for-loop ? – ycx Dec 16 '18 at 16:01
  • I have now, and it worked flawlessly. Thank you! – Soumya Mukhija Dec 17 '18 at 11:26
  • @SoumyaMukhija You're welcome. Please mark this as the correct answer if you think it helped you. Thanks! – ycx Dec 17 '18 at 14:02
0

based on YCX's answer, you can do this for the buttons:

for index, i in enumerate(viewdata):
    vars()['doc'+str(index)]=Button( mainframe, image=docimg, bd=0,cursor='hand1',  command=lambda: openexistingfile(str(i[0])))
    vars()['doc'+str(index)].place(x=cnt, y=70)
    vars()['doc'+str(index)].image=docimg