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()
0

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

wow, thank you so much for your help :D <3
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.

1 Comment

thank you for the reply! i understand what you mean, i will be careful next time :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.