1

I am trying to make a buttons that prints values what i assing to them. In my mind all buttons should print same values on their text value. Instead they all print "4". What is the wright way to solve this?

from tkinter import *

root = Tk()

def printFunc(text):
    print(text)

list=[0,1,2,3,4]

for i in list:

    w = Button(root, text=list[i],command=lambda: printFunc(list[i])).pack()

root.mainloop()
yasinfy
  • 25
  • 5

2 Answers2

1

The solution is to provide a default value at the moment then lambda is constructed

from Tkinter import *


root = Tk()

def printFunc(text):
    print(text)

lst=[0,1,2,3,4]

for i in lst:

    w = Button(root, text=lst[i],command=lambda x=lst[i]: printFunc(x)).pack()

root.mainloop()
rth
  • 2,693
  • 1
  • 20
  • 27
1

This is a very common beginners problem, because you don't understand how lambda works. The solution is to use functools.partial instead of lambda.

from tkinter import *
from functools import partial

root = Tk()

def printFunc(text):
    print(text)

list=[0,1,2,3,4]

for i in list:
    w = Button(root, text=list[i],command=partial(printFunc, list[i]))
    w.pack()

root.mainloop()

Also, always put the pack() on a new line, so that you avoid another very common beginners problem.

Novel
  • 12,855
  • 1
  • 22
  • 38