pygame实现加法计算器
时间: 2023-05-20 17:06:58 浏览: 179
可以使用pygame实现一个简单的加法计算器,以下是示例代码:
```python
import pygame
pygame.init()
# 设置窗口大小和标题
win = pygame.display.set_mode((400, 300))
pygame.display.set_caption("加法计算器")
# 设置字体
font = pygame.font.SysFont("Arial", 30)
# 初始化变量
num1 = ""
num2 = ""
result = ""
# 游戏循环
run = True
while run:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.unicode.isdigit():
if len(num1) < 10:
num1 += event.unicode
elif event.key == pygame.K_BACKSPACE:
num1 = num1[:-1]
elif event.key == pygame.K_RETURN:
if num1 and num2:
result = str(int(num1) + int(num2))
else:
result = ""
elif event.key == pygame.K_ESCAPE:
num1 = ""
num2 = ""
result = ""
else:
pass
# 绘制界面
win.fill((255, 255, 255))
text1 = font.render(num1, True, (0, 0, 0))
text2 = font.render(num2, True, (0, 0, 0))
text3 = font.render(result, True, (0, 0, 0))
win.blit(text1, (50, 50))
win.blit(text2, (50, 100))
win.blit(font.render("+", True, (0, 0, 0)), (150, 75))
win.blit(text3, (200, 75))
pygame.display.update()
pygame.quit()
```
这个加法计算器可以接受用户输入两个数字,按下回车键后会计算它们的和并显示在屏幕上。按下 ESC 键可以清空输入。
阅读全文