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

Pygame Zero中Rect创建报错,screen.draw.filled_rect无法绘制按钮

解决Pygame Zero中绘制Play按钮的TypeError问题

错误根源

你创建Rect对象时只传入了x和y坐标(Rect(100, 50)),这不符合Pygame Zero对矩形对象的要求——合法的rect对象必须同时包含位置和尺寸信息,也就是需要4个参数:x, y, width, height,或者传入一个包含这四个值的元组,否则screen.draw.filled_rect会因无法识别无效的rect对象抛出TypeError: Argument must be rect style object。

修正步骤

  1. 正确定义按钮矩形:补充宽度和高度参数,比如设置按钮宽150、高60:
    play_button = Rect(100, 50, 150, 60)
    
  2. 绘制黄色填充矩形:用修正后的rect对象调用screen.draw.filled_rect:
    screen.draw.filled_rect(play_button, "yellow")
    
  3. 添加按钮文字:通过screen.draw.text在按钮中心绘制文字,确保文字对齐:
    screen.draw.text("Play", center=play_button.center, fontsize=30, color="black")
    

完整示例代码

import pgzrun

# 定义按钮的位置和尺寸
play_button = Rect(100, 50, 150, 60)

def draw():
    screen.clear()
    # 绘制黄色按钮背景
    screen.draw.filled_rect(play_button, "yellow")
    # 绘制按钮文字
    screen.draw.text("Play", center=play_button.center, fontsize=30, color="black")

pgzrun.go()

额外说明

Pygame Zero的Rect类继承自Pygame的pygame.Rect,所以构造规则完全一致:必须提供能确定矩形边界的参数(要么x,y,w,h四个数值,要么包含这四个值的序列/其他rect对象),仅传位置坐标无法生成有效的矩形对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:35:57