You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Pygame中的TypeError: invalid destination position for blit错误?

Fixing the TypeError: invalid destination position for blit in Your Pygame Tag Game

Let's break down the issues in your code and fix them step by step:

1. Broken Text Surface Initialization

Your line creating the text surface has a syntax error that turns text into an invalid tuple instead of a proper Pygame Surface:

text = pyg.surface, test_font.render(PlayerNames[0], True, black)

Remove the misplaced pyg.surface, and also change the text color (black text on a black background will be completely invisible):

text = test_font.render(PlayerNames[0], True, (255, 255, 255))  # White text for visibility

2. Incorrect blit() Arguments

The blit() method expects two core arguments: the surface to draw, and a tuple representing the destination position. Your current call mixes up arguments, splits the position into separate values, and even tries to blit the screen onto itself (which makes no sense).

To make the text look better, we’ll calculate its bounding rectangle to keep it horizontally centered on the screen:

# Get the text's bounding rectangle and center it at (width/2, 50)
text_rect = text.get_rect(center=(width/2, 50))
# Blit the text using this centered rectangle
screen.blit(text, text_rect)

Full Fixed Code

Here's the complete corrected code with all fixes and small quality-of-life improvements:

import pygame as pyg
import time

# Screen initialization
pyg.init()
screen = pyg.display.set_mode((1280, 720), pyg.RESIZABLE)
width, height = screen.get_size()
pygame_icon = pyg.image.load('icon.png')
pyg.display.set_icon(pygame_icon)
pyg.display.set_caption("taggy")
clock = pyg.time.Clock()

black = (0, 0, 0)
background = black
tikker = 0
PlayerNames = ['Player 1', 'Player 2']
test_font = pyg.font.SysFont("Comic Sans MS", 50)
# Fixed text surface creation with visible white color
text = test_font.render(PlayerNames[0], True, (255, 255, 255))

while True:
    for event in pyg.event.get():
        if event.type == pyg.QUIT:
            pyg.quit()  # Cleanly shut down Pygame before exiting
            exit()
    
    # Update screen size every frame so text stays centered if window is resized
    width, height = screen.get_size()
    text_rect = text.get_rect(center=(width/2, 50))
    
    screen.fill(background)
    # Correct blit call with centered text
    screen.blit(text, text_rect)
    
    pyg.display.flip()
    clock.tick(60)

Extra Touches:

  • Added pyg.quit() + exit() for a clean shutdown instead of raw quit()
  • Updated screen size each frame to keep text centered if the player resizes the window

内容的提问来源于stack exchange,提问作者olivier kools

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:52:44