2013-08-20 274 views
1

嘿傢伙第一篇文章,什麼不那麼喜。無論如何,試圖用tkinter製作一個科學計算器,即時通訊並不是很好(而Python是我的第二個適當的任務)。無論如何,大部分的代碼可能是錯誤的,但即時通訊只是一步一個腳印,特別是關注函數add。即時通過按鈕調用它,但我想通過do函數a +。這反過來創建一個數組我可以從中計算。它不斷錯誤,我不知道如何解決它。它真的討厭我現在這樣,如果有人可以幫幫忙,將不勝感激tkinter按鈕按功能調用

from tkinter import* 
from operator import* 

class App: 
    def __init__(self,master):#is the master for the button widgets 
     frame=Frame(master) 
     frame.pack() 
     self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a + 
     self.addition.pack() 
    def add(Y): 
     do("+") 
    def do(X):#will hopefully colaborate all of the inputs 
     cont, i = True, 0 
     store=["+","1","+","2","3","4"] 
     for i in range(5): 
      X=store[0+i] 
      print(store[0+i]) 
      cont = False 
     if cont == False: 
      print(eval_binary_expr(*(store[:].split()))) 
    def get_operator_fn(op):#allows the array to be split to find the operators 
     return { 
      '+' : add, 
      '-' : sub, 
      '*' : mul, 
      '/' : truediv, 
      }[op] 
    def eval_binary_expr(op1, num1, op2, num2): 
     store[1],store[3] = int(num1), int(num2) 
     return get_operator_fn(op2)(num1, num2) 


root=Tk() 
app=App(root) 
root.mainloop()#runs programme 

回答

2

一般來說,在一個類中的每個方法應該採取self作爲第一個參數。名稱self只是一個約定。它不是Python中的關鍵字。但是,當您調用方法(如obj.add(...))時,發送到該方法的第一個參數是實例obj。在方法定義中調用該實例self是一種慣例。因此,所有的方法都需要進行修改,以包括self作爲第一個參數:

class App: 
    def __init__(self, master):#is the master for the button widgets 
     frame=Frame(master) 
     frame.pack() 
     self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a + 
     self.addition.pack() 
    def add(self): 
     self.do("+") 
    def do(self, X): 
     ... 

需要注意的是,當你調用self.do("+"),方法do內,X將被綁定到"+"。後來在這個方法我看到

X=store[0+i] 

將重新綁定X的值store[i]。我不知道你在這裏做什麼,但請注意,這樣做意味着你剛剛丟失了剛剛傳入的"+"值。

+0

即時嘗試按順序將「+」添加到數組所以當我有其他按鈕時,我可以輸入整個方程而不必按每個數字輸入。正如我所說,雖然即時通訊仍然剛剛開始,所以它可能會相當inefficent代碼(和或不工作),但只是頂部幫助了卡車負載我couldent找出爲什麼它wouldent工作。 – akronicillness