Answer the question
In order to leave comments, you need to log in
Why is Tkinter not working properly?
I am creating a calculator on Tkinter. And the program should essentially display the text of the button in the Entry. But this does not happen, but just 0 comes out. Why is this happening?
The code:
from tkinter import *
from tkinter import ttk
root = Tk()
root.title = 'Calc'
root.resizable(width=False, height=False)
display = ttk.Entry(root)
display.grid(row=0, column=0, columnspan=3)
buttons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
row_position = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4]
column_position = [0, 1, 2, 0, 1, 2, 0, 1, 2, 1]
for id in range(0, len(buttons)):
ttk.Button(root, text=buttons[id], command=lambda:display.insert(0,buttons[id])).grid(row=row_position[id], column=column_position[id])
root.mainloop()
Answer the question
In order to leave comments, you need to log in
It's not about tkinter. The reason is that when lambda is defined inside a loop, it must be passed the loop variable explicitly. Otherwise, each lambda will contain the value of the variable in the last iteration. Write like this and it will work:
ttk.Button(root,
text=buttons[id],
command=lambda id=id: display.insert(0, buttons[id])).grid(row=row_position[id],
column=column_position[id])
I don't know for sure, but try replacing this: display.insert(0,buttons[id])
with thisdisplay.insert(1.0,buttons[id])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question