Question

I'm writing a simple calculator by using python 3.2 and Tkinter libery. When I'm run my programm, it print in text field numbers which need to be printed only after event. What i did wrong?

from tkinter import Button, Entry, Tk, Widget
from calculate import calculate

def output():
    equation = text.get()
    result = calculate(equation)
    if result != False:
        text.delete(0, 100)
        text.insert(0, result)
    else:
        text.delete(0, 100)
        text.insert(0, 'Error')

def insert_num(i):
    text.insert(100, i)

root=Tk()
root.config(width=265, height = 320)

text=Entry(root, font='Arial 14')
text.config(width=22)
text.place(x=10, y=20)

class Num(Widget):
    def __init__(self, root, text, font, width, height, x, y, command):
        self.widget = Button(root, text=text, font=font, command=command)
        self.widget.config(width=width, height=height)
        self.widget.place(x=x, y=y)

font = 'Arial 14'
plus = Num(root, '+', font, 3, 1, 10, 50+10, None)
minus = Num(root, '-', font, 3, 1, 10, 100+10, None)
divide = Num(root, '/', font, 3, 1, 10, 150+10, None)
multiple = Num(root, '*', font, 3, 1, 10, 200+10, None)

list = ['','','','','','','','','']
x = 50+10; y = 100+10
for i in range(0, 9):
    list[i] = Button(root, text=i+1, font='Arial 14')
    list[i].bind('<Button-1>', insert_num(i+1))
    list[i].config(width = 3, height = 1)
    list[i].place(x=x, y=y)
    x = x + 50
    if i == 2 or i == 5:
        x = 50+10; y = y + 40+10

root.mainloop()

Output:

123456789
Was it helpful?

Solution

The second argument of list[i].bind() should be a function, not a call to a function. With insert_num(i+1) you are calling to the function, and binding None to the click event. Replace insert_num with this:

def insert_num(i):
    return lambda event: text.insert(100, i)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top