用Python(推荐导入PySimpleGUI库)写一个面积计算器,首先在主界面选择需要计算矩形、三角形、圆形哪种图形的面积,然后根据选择跳转其对应的界面输入需要的数据并给出结果,得到结果后可以选择返回主界面继续使用计算器并且系统不会崩溃
时间: 2023-12-03 19:47:04 浏览: 39
好的,以下是代码实现:
```python
import PySimpleGUI as sg
import math
# 定义主界面
def main_menu():
layout = [
[sg.Text('请选择需要计算的图形')],
[sg.Button('矩形', key='rectangle'), sg.Button('三角形', key='triangle'), sg.Button('圆形', key='circle')],
[sg.Text('结果:'), sg.Output(size=(30, 1))],
[sg.Button('退出', key='exit')]
]
return sg.Window('面积计算器', layout=layout, finalize=True)
# 定义矩形计算界面
def rectangle_menu():
layout = [
[sg.Text('请输入矩形的长和宽')],
[sg.Text('长:'), sg.InputText(key='length')],
[sg.Text('宽:'), sg.InputText(key='width')],
[sg.Button('计算', key='calculate'), sg.Button('返回', key='back')]
]
return sg.Window('矩形面积计算', layout=layout, finalize=True)
# 定义三角形计算界面
def triangle_menu():
layout = [
[sg.Text('请输入三角形的底和高')],
[sg.Text('底:'), sg.InputText(key='base')],
[sg.Text('高:'), sg.InputText(key='height')],
[sg.Button('计算', key='calculate'), sg.Button('返回', key='back')]
]
return sg.Window('三角形面积计算', layout=layout, finalize=True)
# 定义圆形计算界面
def circle_menu():
layout = [
[sg.Text('请输入圆的半径')],
[sg.Text('半径:'), sg.InputText(key='radius')],
[sg.Button('计算', key='calculate'), sg.Button('返回', key='back')]
]
return sg.Window('圆形面积计算', layout=layout, finalize=True)
# 运行主程序
def run():
main_window = main_menu()
rectangle_window, triangle_window, circle_window = None, None, None
while True:
window, event, values = sg.read_all_windows()
if window == main_window:
if event in (sg.WIN_CLOSED, 'exit'):
break
elif event == 'rectangle':
rectangle_window = rectangle_menu()
main_window.hide()
elif event == 'triangle':
triangle_window = triangle_menu()
main_window.hide()
elif event == 'circle':
circle_window = circle_menu()
main_window.hide()
elif window == rectangle_window:
if event in (sg.WIN_CLOSED, 'back'):
rectangle_window.close()
main_window.un_hide()
elif event == 'calculate':
try:
length = float(values['length'])
width = float(values['width'])
area = length * width
print(f'矩形面积为 {area:.2f}')
except ValueError:
print('请输入正确的数字')
elif window == triangle_window:
if event in (sg.WIN_CLOSED, 'back'):
triangle_window.close()
main_window.un_hide()
elif event == 'calculate':
try:
base = float(values['base'])
height = float(values['height'])
area = base * height / 2
print(f'三角形面积为 {area:.2f}')
except ValueError:
print('请输入正确的数字')
elif window == circle_window:
if event in (sg.WIN_CLOSED, 'back'):
circle_window.close()
main_window.un_hide()
elif event == 'calculate':
try:
radius = float(values['radius'])
area = math.pi * radius ** 2
print(f'圆形面积为 {area:.2f}')
except ValueError:
print('请输入正确的数字')
main_window.close()
if __name__ == '__main__':
run()
```
运行代码后,会弹出一个主界面,选择需要计算的图形后进入对应的计算界面。计算完毕后可以选择返回主界面或退出程序。其中使用了PySimpleGUI库来构建界面。
阅读全文