我已正确安装所有依赖项(SDL2、SDL2_TTF、pysdl2)。 我尝试仅提供字体的文件名,并尝试对完整路径进行硬编码。字体与 python 文件位于同一目录中。
import sys
try:
from sdl2 import *
import sdl2.ext as sdl2ext
import sdl2.sdlttf as sdlttf
except ImportError:
import traceback
traceback.print_exc()
sys.exit(1)
def run():
sdl2ext.init()
sdlttf.TTF_Init()
RESOURCES = sdl2ext.Resources(__file__, "")
# print(RESOURCES.get_path("arial.ttf"))
font = sdlttf.TTF_OpenFont(RESOURCES.get_path("arial.ttf"), 24)
window = sdl2ext.Window("SDL_TTF test", size=(800, 600))
message = sdlttf.TTF_RenderText_Solid(font, "Hello World", (255, 255, 255))
window.show()
running = True
while running:
events = sdl2ext.get_events()
for event in events:
if event.type == SDL_QUIT:
running = False
break
window.refresh()
return 0
if __name__ == "__main__":
sys.exit(run())
退货:
Traceback (most recent call last):
File "sdl2_test.py", line 32, in <module>
sys.exit(run())
File "sdl2_test.py", line 17, in run
font = sdlttf.TTF_OpenFont(RESOURCES.get_path("arial.ttf"), 24)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
我明白了。由于我使用的是 Python 3,由于 Python 3 中用于表示字符串的标准类型,类型不正确。我通过使用 str.encode()
解决了这个问题