Skip to main content
 首页 » 编程设计

Python 游戏 "an integer is required"

2025年05月04日41arxive

我有一个使用 gTTS、pygame 和 os 模块的函数:

from gtts import gTTS 
import pygame as pg 
from os import remove as OSremove 
 
music = pg.mixer.music 
 
def speak(x): 
     sound = gTTS(text=x, lang="pl") 
     sound.save("temp.mp3") 
     pg.mixer.init() 
     music.load("temp.mp3") 
     music.play("temp.mp3") 
     pg.quit() 
     OSremove("temp.mp3") 

我收到一个错误:TypeError:需要一个整数(得到类型 str)。 Image here because I have 5 rep

请您参考如下方法:

好的,就目前而言,上面的答案是正确的,但让我们更深入地了解一下,因为您显然是新手。

首先,当您收到错误消息时,阅读。在这种情况下,它告诉您它需要一个整数,而您给它一个字符串。所以,很明显,您误会了什么。

接下来,看看文档。 Google pygame.mixer.music.play,它会立即弹出。

https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.play

接下来,看文档。在这种情况下,它表示:

play 有两个参数,loops 和 start,它们都默认为 0。没有字符串——所以你给它错误的论点。

进一步查看 Google 结果,您会看到一个 SO 问题:How play mp3 with pygame

这将引导您找到另一个 SO 答案中的一些示例代码。