2013-03-02 191 views
0

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

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

list[i].bind()第二个参数应该是一个函数,而不是一个函数的调用。使用insert_num(i+1)您正在调用该函数,并将None绑定到单击事件。用这个替换insert_num

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

哦,那么简单。非常感谢! – 2013-03-02 15:39:31

相关问题