我有以下代码(这是一个计算器程序):
import pygame
import operator
pygame.init()
screen = pygame.display.set_mode((400, 711))
pygame.display.set_caption("INIX")
Calculator_Screen = pygame.image.load("Calculator.Screen.png")
op = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
}
def calculator_module():
events = list(pygame.event.get())
for event in events:
if event.type == pygame.QUIT:
Calculator = False
return Calculator
if event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
if x > 17 and x < 107 and y > 445 and y < 530: #1
return "1"
elif x > 108 and x < 198 and y > 445 and y < 530: #2
return "2"
elif x > 199 and x < 290 and y > 445 and y < 530: #3
return "3"
elif x > 17 and x < 107 and y > 336 and y < 443: #4
return "4"
elif x > 108 and x < 198 and y > 336 and y < 443: #5
return "5"
elif x > 199 and x < 290 and y > 336 and y < 443: #6
return "6"
elif x > 17 and x < 107 and y > 268 and y < 334: #7
return "7"
elif x > 108 and x < 198 and y > 268 and y < 334: #8
return "8"
elif x > 199 and x < 290 and y > 268 and y < 334: #9
return "9"
elif x > 17 and x < 107 and y > 532 and y < 620: #0
return "0"
elif x > 199 and x < 290 and y > 532 and y < 620: #=
return "="
elif x > 292 and x < 380 and y > 532 and y < 620: #+
return "+"
elif x > 292 and x < 380 and y > 445 and y < 530: #-
return "-"
elif x > 292 and x < 380 and y > 268 and y < 334: #/
return "/"
elif x > 292 and x < 380 and y > 336 and y < 443: #x
return "*"
Calculator = True
while Calculator:
screen.blit(Calculator_Screen, (0, 0))
pygame.display.update()
events = list(pygame.event.get())
for event in events:
if event.type == pygame.QUIT:
Calculator = False
if event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
if x > 180 and x < 218 and y > 670 and y < 708:
Calculator = False
while True:
current = 0
num1 = 0
num2 = 0
while current not in op:
num1 = num1*10 + int(current)
current = calculator_module()
last_op = current
current = 0
while current != "=":
if current in op:
num1 = op[last_op](num1, num2)
last_op = current
num2 = 0
else:
num2 = num2*10 + int(current)
current = calculator_module()
res = op[last_op](num1, num2)
print(res)
每当我运行此代码并按下按钮时,我会收到以下错误:
num1 = num1*10 + int(current)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
我不知道为什么我收到此错误,因为我根本不使用None
感谢。
答案 0 :(得分:3)
请注意,在某些情况下,您的函数calculator_module()
不会return
(例如当events
为空时),因此隐式会返回{{ 1}}。
在这种情况下,您将None
作为None
,这会导致错误。
要解决此问题,请确保您的函数current
在所有执行路径中返回一个值。
编辑,例如:
calculator_module()
编辑#2:我应该注意到你看起来很奇怪:
def calculator_module():
events = list(pygame.event.get())
if not events: # check if the list is empty
return 0
for event in events:
if event.type == pygame.QUIT:
Calculator = False
return Calculator
elif event.type == pygame.MOUSEBUTTONUP:
...
... # all your other elif go here
...
else:
return 0
因为您实际上永远不会迭代超过单个事件。因为你for event in events:
以防万一......所以你应该重新考虑你的逻辑流程。