V
V
VuztreeCalan2018-08-07 22:26:28
Python
VuztreeCalan, 2018-08-07 22:26:28

How to create buttons in a loop with a different command argument (Tkinter Python3)?

There is a code that iterates over files in a folder, puts .jpg in the images list, and folders (I made it with a crutch, because I don’t know how to make the correct condition) in the dirs list.
Next is a loop that creates as many buttons as there are folders found, but the task is to send the button to the file in the folder whose index was specified during the for iteration, and I didn’t succeed in doing this, I think it will be clearer in the code that I wanted to do, here it is:

import os
import shutil
from tkinter import *

root = Tk()
root.title("Sort Images")
root.geometry("1920x1080")

def copyImageToDir (dirIndex):
    shutil.copy(images[0], dirs[dirIndex])

dirs = []
images = []
for file in os.listdir():
    if (file.endswith(".jpg")):
        images.append(file)
    elif not (file.endswith(".py")):
        dirs.append(file)


xCord = .4
for dirIndex, dirName in enumerate(dirs):
    buttonName = Button(text="Поместить в папку: " + dirName, cursor="cross", command=lambda: copyImageToDir(dirIndex))
    buttonName.place(relx=xCord, rely=.80, anchor="center")
    xCord += .1

root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-08-07
@VuztreeCalan

Use a closure

...command=lambda dirIndex=dirIndex: copyImageToDir(dirIndex))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question