在Python中,你可以使用不同的库来绘制矩形,以下是使用Pygame和matplotlib两个库绘制矩形的示例代码:
使用Pygame绘制矩形
import pygameimport syspygame.init()screen = pygame.display.set_mode([640, 480]) 设置窗口大小screen.fill([255, 255, 255]) 用白色填充窗口背景pygame.draw.rect(screen, [255, 0, 0], [150, 200, 300, 200], 0) 绘制矩形pygame.display.flip() 更新显示running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falsepygame.quit() 退出游戏

使用matplotlib绘制矩形
import matplotlib.pyplot as pltimport matplotlib.patches as patchesfig1 = plt.figure()ax1 = fig1.add_subplot(111, aspect='equal') 设置等比例显示ax1.add_patch(patches.Rectangle((0.1, 0.1), 0.5, 0.5)) 绘制矩形fig1.savefig('rect1.png', dpi=90, bbox_inches='tight') 保存图像
以上代码分别展示了如何使用Pygame和matplotlib库在Python中绘制矩形。Pygame用于创建游戏窗口并绘制图形,而matplotlib用于创建静态图像。
