1

I'm trying to make a little file explorer with just buttons, I'm still in the early stages and want to make a function prints which button was pressed and came up with this:

import tkinter as tk

buttons = []

window = tk.Tk()
window.geometry("200x100")
def open(button):
    print(button)

def list(titles):
    i=0
    while i<(len(titles)):
        btn = tk.Button(text=titles[i], width=20, command=lambda: open(i))
        buttons.append(btn)
        buttons[i].grid(row=i, column=1)
        print(f"adding {titles[i]}")
        i=i+1

list(["title1", "title2", "title3"])
window.mainloop()

There's one problem: It always prints 3. I think I know what the problem is, i always stays 3 after generating the button so it passes 3 to the function, but I don't know how to solve it. I used the lambda cuz I cant pass parameters just using open(i) and found the lambda-solution to that on this question .

Can someone help? Tnx!

JasperDG
  • 137
  • 1
  • 3
  • 7

1 Answers1

1

Because it over writes the commands on one button when you assign it again. Do:

import tkinter as tk

buttons = []

window = tk.Tk()
window.geometry("200x100")

def open(button):
    print(button)

def list(titles):
    btn = tk.Button(text=titles[0], width=20, command=lambda: open(1))
    buttons.append(btn)
    buttons[0].grid(row=1, column=1)
    print(f"adding {titles[0]}")

    btn = tk.Button(text=titles[1], width=20, command=lambda: open(2))
    buttons.append(btn)
    buttons[1].grid(row=2, column=1)
    print(f"adding {titles[1]}")

    btn = tk.Button(text=titles[2], width=20, command=lambda: open(2))
    buttons.append(btn)
    buttons[2].grid(row=3, column=1)
    print(f"adding {titles[2]}")


list(["title1", "title2", "title3"])
window.mainloop()
Tkinter Lover
  • 835
  • 3
  • 19