【发布时间】:2013-08-29 14:30:37
【问题描述】:
嘿,再次使用相同的代码,经过精心编辑,效果更好。无论如何尝试将按钮输入添加到数组中并且有效。不起作用的是,每次我调用函数 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())))
【问题讨论】:
-
我完全不确定您要做什么...但是有些 cmets。首先
range(1)等于[0]我不认为你想要。你希望你的代码做什么? -
它最终将成为一个计算器我试图做的是将屏幕上的一个按钮变成一个我可以计算的数组,但即使这样我稍后也使用了一个拆分(不在提取)所以我需要使用字符串而不是数组。无论如何,按下按钮会保存到数组(self.store)中,但作为一个函数,它是一个局部变量,因此每次我按下一个新按钮时,我在数组中的位置都会发生变化,但是它不会保存我的最后一个按钮,因为它是本地的。我想知道如何让 self.store 保持它的价值。
-
self.store确实保持它的价值。您只需在do中每次都覆盖它。
标签: python arrays python-3.x tkinter