Pygame项目报错TypeError:'pygame.Surface'对象不可下标访问,附代码求助
Hey there, let's break down this error and fix it step by step.
First, the root cause of this error is that you're trying to use subscript notation (like something[0]) on a pygame.Surface object—and Surfaces don't support that kind of access.
Looking at your code:
def text(window, text, loc, color, font_size): font = pygame.font.Font('Fonts/Sticky_koala-Regular.ttf', font_size) text = font.render(text, True, color) window.blit(text, loc) return (text) text(window, "/" + numerictext(maxvariable), (variablebox[0][0] + variablebox[1], popuprect.top + 80), (255, 255, 255), 36)
Your text function returns the result of font.render(), which is a pygame.Surface (this is the rendered image of your text, not the original string). If anywhere else in your code you take that return value and try to index into it (e.g., rendered_text = text(...); print(rendered_text[0])), that's exactly what's triggering the error.
Here are the fixes you can apply:
Option 1: Remove the return statement if you don't need the Surface
Since you're already callingwindow.blit()inside the function to draw the text to the window, you might not even need to return the Surface. Just delete thereturn (text)line, and you won't accidentally try to index into it later.Option 2: Adjust how you use the returned Surface
If you do need to keep the returned Surface (for things like getting its size), use Surface methods instead of subscripts. For example, usetext_surface.get_width()ortext_surface.get_height()instead of trying to index into it.Bonus: Clean up variable names to avoid confusion
Your function usestextboth as a parameter (the input string) and as a local variable (the rendered Surface). This isn't an error, but it's easy to mix up. Renaming the local variable makes your code clearer:def draw_text(window, text_str, loc, color, font_size): font = pygame.font.Font('Fonts/Sticky_koala-Regular.ttf', font_size) text_surface = font.render(text_str, True, color) window.blit(text_surface, loc) # Keep this line only if you need the Surface elsewhere return text_surface
Finally, double-check all places where you call this function—make sure none of them are trying to use subscripts on the returned value.
内容的提问来源于stack exchange,提问作者Koala's Maker

