# Python實現的簡單計算器

GUI執行截圖：

PyQt4裡的單行文字框：

``````self.line_edit = QtGui.QLineEdit()  # create an object of single line edit box
self.line_edit.text()  # get texts in the edit box
self.line_setText("text")  # set the text of edit box``````

``````self.main_layout = QtGui.QGridLayout()
# set layout to window
self.setLayout(self.main_layout)``````

``````#calculate from stack, return result string
def calculate_from_stack(suffix_stack):
error_str = "error"
nan_str = "NaN"
if None == suffix_stack:
print "stack is empty!"
return error_str
data = suffix_stack.get_data()
calculate_stack = ExpStack.ExpStack()
for ele in data:
if is_number_str(ele):
calculate_stack.push(ele)
elif is_calculator_option(ele):
if calculate_stack.size() < 2:
print "Wrong suffix exps."
print_calculator_stack(suffix_stack)
return error_str
try:
num1 = float(calculate_stack.get_top())
calculate_stack.pop()
num2 = float(calculate_stack.get_top())
calculate_stack.pop()
if " " == ele:
calculate_stack.push(num1 num2)
elif "-" == ele:
calculate_stack.push(num2-num1)
elif "*" == ele:
calculate_stack.push(num2*num1)
elif "/" == ele:
calculate_stack.push(num2/num1)
elif "^" == ele:
calculate_stack.push(num2**num1)
else:
print "Unknown calculator operator", ele
return error_str
except TypeError, e:
print "type error:", e
return error_str
except ValueError, e:
print "value error:", e
return error_str
except ZeroDivisionError, e:
print "divide zero error:", e
return nan_str
if 1 == calculate_stack.size():
return str(calculate_stack.get_top())
else:
print "Unknown error, calculate stack:"
print_calculator_stack(calculate_stack)
return error_str``````