为什么Entry.insert没有事件执行?

时间:2013-03-02 14:58:46

标签: python tkinter insert tkinter-entry

我正在使用python 3.2和Tkinter libery编写一个简单的计算器。 当我运行我的程序时,它打印在文本字段编号中,只有在事件发生后才需要打印。我做错了什么?

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

输出:

123456789

1 个答案:

答案 0 :(得分:1)

list[i].bind()的第二个参数应该是一个函数,而不是对函数的调用。使用insert_num(i+1)调用该函数,并将None绑定到click事件。将insert_num替换为:

def insert_num(i):
    return lambda event: text.insert(100, i)