tkinter, problem with distinguishing buttons in menu

Question:

I have a problem with my code. I’m trying to create several buttons in a loop and assign them a value from x [i], but the value of "i" changes in the command of all buttons.

import tkinter as tk

def buttons():
    x = [11, 22, 34, 45, 56]
    for i in range(len(x)):
        button.menu.add_cascade(label=i+1, command=lambda: test(x[i]))


def test(text):
    print(text)


window = tk.Tk()
window.geometry("300x130")

button = tk.Menubutton(window, text='Button', relief=tk.RAISED)
button.pack()
button.menu = tk.Menu(button, tearoff=0)
button['menu'] = button.menu

buttons()

window.mainloop()
Asked By: Kornel

||

Answers:

import tkinter as tk

def buttons():
    x = [11, 22, 34, 45, 56]
    for i in range(len(x)):
        button.menu.add_cascade(label=i+1, command=lambda i=i: test(x[i]))


def test(text):
    print(text)


window = tk.Tk()
window.geometry("300x130")

button = tk.Menubutton(window, text='Button', relief=tk.RAISED)
button.pack()
button.menu = tk.Menu(button, tearoff=0)
button['menu'] = button.menu

buttons()

window.mainloop()

To understand why this works, read.

Answered By: Thingamabobs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.