在Python中,你可以使用不同的库来绘制矩形,以下是使用Pygame和matplotlib两个库绘制矩形的示例代码:
使用Pygame绘制矩形
import pygame
import sys
pygame.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 = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit() 退出游戏
使用matplotlib绘制矩形
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = 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用于创建静态图像。