1

At the below example, the buttons are created according to the files in a spesific directory. And i added a print function to the buttons. What i wanted to do is, when i click each button, every button should print the related file. But according to the below codes, when i click every button, they print the same file name which is the last item of the file list. Can you help me to show me what's missing in these codes?

from tkinter import *
import os


class Application:
    def __init__(self):
        self.window = Tk()

        self.frame = Frame()
        self.frame.grid(row=0, column=0)

        self.widgets()
        self.mainloop = self.window.mainloop()

    def widgets(self):
        files = self.path_operations()
        for i in range(len(files)):
            button = Button(self.frame, text="button{}".format(i))
            button.grid(row=0, column=i)
            button.configure(command=lambda: print(files[i]))

    @staticmethod
    def path_operations():
        path = "D:\TCK\\Notlar\İş Başvurusu Belgeleri"
        file_list = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path, i))]
        return file_list


a = Application()
dildeolupbiten
  • 1,314
  • 1
  • 15
  • 27

1 Answers1

1

The program needs somehow to know what file to print, but i is shared and changes. Here's a technique:

def widgets(self):
    files = self.path_operations()
    for i in range(len(files)):
        button = Button(self.frame, text="button{}".format(i))
        button.grid(row=0, column=i)
        button.configure(command=self.make_print(files[i]))

@staticmethod
def make_print(file):
    def local_print ():
        print(file)
    return local_print
Walle Cyril
  • 3,087
  • 4
  • 23
  • 55