使用Python创建一个简单的加法计算器可以通过多种方法实现,以下是两种常见的方法:
方法一:使用函数
```python
def add_numbers(a, b):
return a + b
def main():
while True:
num1 = input("请输入第一个数字:")
num2 = input("请输入第二个数字:")
if num1.isdigit() and num2.isdigit():
result = add_numbers(int(num1), int(num2))
print(f"结果是:{result}")
else:
print("输入错误,请输入数字。")
continue_calculation = input("是否继续计算?(y/n):")
if continue_calculation.lower() != 'y':
break
if __name__ == "__main__":
main()
方法二:使用tkinter创建图形界面
```python
from tkinter import *
def calculate():
try:
num1 = int(text1.get(1.0, END))
num2 = int(text2.get(1.0, END))
result = num1 + num2
text3.delete(1.0, END)
text3.insert(INSERT, result)
except ValueError:
text3.delete(1.0, END)
text3.insert(INSERT, "输入错误,请输入数字。")
root = Tk()
root.title("加法计算器")
label1 = Label(root, text="第一个数字:")
label1.grid(row=0, column=0)
text1 = Text(root, width=30, height=1)
text1.grid(row=1, column=0)
label2 = Label(root, text="第二个数字:")
label2.grid(row=2, column=0)
text2 = Text(root, width=30, height=1)
text2.grid(row=3, column=0)
label3 = Label(root, text="结果:")
label3.grid(row=4, column=0)
text3 = Text(root, width=30, height=1)
text3.grid(row=5, column=0)
calculate_button = Button(root, text="计算", command=calculate)
calculate_button.grid(row=6, column=0, columnspan=2)
root.mainloop()
以上两种方法都可以实现加法计算器的功能。第一种方法使用函数处理输入和计算,第二种方法使用tkinter库创建图形用户界面。你可以根据自己的需求选择合适的方法。