0

I want to use tk to do this: enter image description here

Left text and Right button in one row,text data store in a list,so i use loop:

  for file in listname:
    fr = Frame(app)
    Label(fr,text = file).grid(row =row,column=0)
    Button(fr,text = 'download',command =lambda: download(file)).grid(row = row,column=3)

But when I click one button,the parm is always the last elem in list,so what can I do to create button with different parm in one loop?

turingF
  • 51
  • 1
  • 6

2 Answers2

0

Instead of using lambda, try using partial. Include from functools import partial at the top of your code, and replace all calls like

lambda: download(file)

with

partial(dowload, file)

The link below should explain to you why this works.

How does the functools partial work in Python?

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
0

Your lambda is not correct.

 import tkinter as tk

from tkinter import ttk

listname = ['f1', 'f2', 'f3']


def download(file):
    print(file)


win = tk.Tk()
fr = tk.Frame(win)
fr.grid(row=0, column=0)
for row, file in enumerate(listname):
    tk.Label(fr, text=file).grid(row=row, column=0)
    tk.Button(fr, text='download',
              command=lambda f=file: download(f)).grid(row=row, column=1)

win.mainloop()
10SecTom
  • 2,484
  • 4
  • 22
  • 26