0

嘿,再次使用相同的代码,编辑得很好,所以效果更好。无论如何尝试将按钮输入添加到数组中并且有效。不起作用的是,每次我调用函数 do() 时,由于它们是本地的,所以值会重置。我试图通过使用 self.store 数组使其成为全局(在类内)来解决这个问题。这似乎没有解决问题,所以如果有人可以提供帮助,将不胜感激这里是相关代码

def __init__(self,master):#is the master for the button widgets
        self.count=0
        self.store=["0"]
        frame=Frame(master)
        frame.pack()
        self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
        self.addition.pack()
        self.subtraction = Button(frame, text="-", command=self.sub)#when clicked sends a call back for a -
        self.subtraction.pack()
        self.equate = Button(frame, text="=", command=self.equate)#when clicked sends a call back for a =
        self.equate.pack()
        self.one = Button(frame, text="1", command=self.one)#when clicked sends a call back for a -
        self.one.pack()

def add(self):
    self.do("+")
    self.count=self.count+1

def sub(self):
    self.do("-")
    self.count=self.count+1

def equate(self):
    self.do("=")

def one(self):
    self.do("1")
    self.count=self.count+1

def do(self, X):#will hopefully colaborate all of the inputs
    cont, num = True, 0
    strstore="3 + 8"#temporarily used to make sure the calculating works
    self.store=["2","1","+","2","3","4"]#holds the numbers used to calculate.
    for num in range(1):
        if X == "=":
            cont = False
        self.store[self.count]=X
        print(self.store[self.count])
        print(self.store[:])#test code
    if cont == False:
        print(self.eval_binary_expr(*(strstore.split())))  
4

1 回答 1

0
self.store=["2","1","+","2","3","4"]

如果你在 do 函数中这样初始化,self.store 会在你每次调用 do(X ) 如果您不希望它被覆盖,请在 do 函数之外对其进行初始化。

但是,如果您想向列表添加值,请使用 append()、extend 或 += 运算符:

self.store+=["2","1","+","2","3","4"]

(如果您希望它只执行一次,请在构造函数中执行,__init__ 函数!)

还,

self.store[self.count]=X

如果您尝试追加到列表 self.store 的 END,您应该这样做:

self.store.append(X)

这样,您就不需要计算任何东西,但有可能忘记增量并用 X 替换值而不是附加 X。

如上所述,range(1),它是 0...

让我们换一种方式:

def do(self, X):
    cont, num = True, 0
    liststore=['3', '+', '8']#splitting your string.
    #initialize str.store elsewhere!

    if X == "=":    
        cont = False
    self.store.append("X")
    print(self.store[-1])#getting the last
    print(self.store)#the same as self.store[:]
    if cont == False:
        print(self.eval_binary_expr(*(liststore)))  

更简单,而且可能更好。最后一件事:在 Python 中,您通常使用列表(如 self.store),而不是数组(来自模块数组)

于 2013-08-27T20:59:42.273 回答