2013-03-02 232 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

相關問題