0

I want to create a PanedWindow with variable number of panes including a child label bound to a function that prints the name of that label to the screen. My code is:

from tkinter import *
from tkinter import ttk

n = 6
root = Tk()
root.geometry('250x500+100+100')

p = ttk.Panedwindow(root, orient=VERTICAL)
p.grid(column=0, row=0, sticky=(N, S, W, E))


def write(message):
    print(message)

for i in range(n):
    message = 'This is label number %d' %i
    pane = ttk.Labelframe(p, width=25)
    p.add(pane)
    label = ttk.Label(pane, width=10, text='Label %d' %i, relief='solid', cursor='hand2')
    label.bind('<Button-1>', lambda e: write(message))
    label.grid(padx=5, pady=5)

root.mainloop()

But no matter which label is clicked the output corresponds to the last label. How can I solve this problem?

Mohammadreza
  • 79
  • 2
  • 9
  • 1
    Change `lambda e:` to `lambda e, message = message:`. See [this question](https://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda) for more information. – Henry Feb 04 '22 at 22:13
  • It worked. Thanks a lot. I tried `lambda e message=message:` but I don't know what differences `,` makes after e in `lambda e message=message:`? – Mohammadreza Feb 05 '22 at 05:28
  • 1
    The first is not valid syntax, the second is. The part after `lambda` and before `:` are the parameters that you'd have in a normal function. You write `def functionName(a,b,c)`, not `def functionName(a b c)` as the second is not valid syntax. – Henry Feb 05 '22 at 15:37
  • Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – Karl Knechtel Aug 19 '22 at 02:45

0 Answers0