Reputation: 179
I'm trying to create a calculator in Tkinter. Although my current code works well to create the buttons with the correct number on each button since the function is only called after the iteration creating the variables is done, x is always 8, and thus all buttons have a value of 8. How could I circumvent this problem?
I tried without using lambda to call the function, but then the buttons don't even work at all, I'm not really sure why.
Heres the basic code:
from tkinter import *
window=Tk()
ButtonFrame=Frame(window)
ButtonFrame.place(x=100,y=100)
def NumPressed (Digit):
print(Digit)
for y in range(3):
for x in range(3):
NumTXT=y*3+x
Buttonx=Button(ButtonFrame,text=NumTXT,command=lambda:NumPressed(NumTXT))
Buttonx.grid(row=y,column=x)
Upvotes: 0
Views: 43
Reputation: 7176
It has to do with default values in the lambda function. After the buttons are all created the NumTXT
variable == 8. Each time you press a button it uses the current value of NumTXT
.
You can fix this by giving the lambda function a default value which doesn't change:
command=lambda x=NumTXT: NumPressed(x)
^
# Set default value
then each button will have a lambda function with a default value as NumTXT
was at button creation.
Upvotes: 1