我正在尝试在 pygame 中制作一个计算器。我用列表理解制作了数学内容:
[a - b for a, b in zip(numbers, numbers[1:])]
,
但是在 Pygame 窗口上,每按三次任何数学符号就会给出:
TypeError: unsupported operand type(s) for -: 'list' and 'int'
我的代码:
import pygame
pygame.font.init()
width,height=1200,650
win=pygame.display.set_mode((width,height))
bg=pygame.Rect(0,0,width,height)
Npad_w, Npad_h=75,75
number1=0
font=pygame.font.SysFont("comic sans",50)
def draw(Npad1,Npad_sub,number_text):
pygame.draw.rect(win, "dark red", bg)
pygame.draw.rect(win,"pink",Npad1)
pygame.draw.rect(win,"pink",Npad_sub)
text=font.render(number_text,1,"white")
win.blit(text,(width/2-200,height/2-Npad_h*3))
pygame.display.update()
def main():
run = True
Npad1=pygame.Rect(width/2-300,height/2-Npad_h,Npad_w,Npad_h)
Npad_sub=pygame.Rect(width/2-300,height/2-Npad_h+100,Npad_w*2,Npad_h)
number_text=""
number=[]
second=False
numbers=[]
times=0
action=0
times_pressed=1
clock=pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
break
if event.type == pygame.MOUSEBUTTONDOWN:
mouseX,mouseY=pygame.mouse.get_pos()
if Npad1.collidepoint(pygame.mouse.get_pos()) :
number.append("1")
print(number)
number_text="".join(number)
mouseX=0
mouseY=0
elif Npad_sub.collidepoint(pygame.mouse.get_pos()):
if second == False and number != "":
times_pressed+=1
numbers.append(int(number_text))
number_text=""
number.clear()
times += 1
if times_pressed<=2:
action = 1
if times ==2 and action==1:
number1=([a - b for a, b in zip(numbers, numbers[1:])])
print(number1)
numbers.clear()
numbers.append(number1)
times = 1
times_pressed+=1
draw(Npad1,Npad_sub,number_text)
pygame.quit()
if __name__ == "__main__":
main()
如果大家有什么想法,请反馈。
(这是我可以编写的最小代码,并且可以重现,抱歉)
问题在这里:
numbers.append(number1)
- 您将 number1
(这是一个 list
)附加到 numbers
,它只需要整数。如果你想连接列表,你应该使用 extend
,如下所示:
numbers.extend(number1)