数组不保存输入

时间:2013-08-27 01:02:11

标签: python arrays python-3.x tkinter

嘿,使用相同的代码再次回来,经过精心编辑,因此效果更好。无论如何试图将按钮输入添加到数组中并且可行。什么不起作用的事实是每次我调用函数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())))  

1 个答案:

答案 0 :(得分:0)

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

如果你在do函数中以这种方式初始化它,每次你调用时,self.store将被重置为[“2”,“1”,“+”,“2”,“3”,“4”]做(X) 如果您不希望覆盖它,请在do函数之外初始化它。

但是如果要为列表添加值,请使用append(),extend或+ = operator:

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

(如果你只希望它只做一次,在构造函数中执行,__ init__函数!)

self.store[self.count]=X

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

self.store.append(X)

通过这种方式,您不需要计算任何内容,可能会忘记增量并将值替换为X而不是附加X.

如上所述,范围(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),而不是数组(来自模块数组)

相关问题