赞
踩
1、建立一个窗口
import pygame
#模块初始化
pygame.init()
#创建一个窗口,窗口大小为640*480
screen=pygame.display.set_mode([640,480])
#定义窗口的标题为'Draw'
pygame.display.set_caption('Draw')
#用白色填充窗口
screen.fill((255,255,255))
2、退出窗口
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
event.get()函数获取事件队列,即把捕获到的事件放入一个队列,然后一一执行。
3、画圆,矩形,椭圆
说明文档链接如下:
4、当按下键盘上的按键,在频幕上随机画出圆,矩形或者椭圆,按【退出键】退出程序
#!usr/bin/env python
#coding=utf-8
import pygame
import sys
import random
screen_size = (640, 480)
backgroundcolor = (255, 127, 255)
#pygame初始化
pygame.init()
#创建一个窗口
screen = pygame.display.set_mode(screen_size, 0, 32)
pygame.display.set_caption('Draw rect and circle')
#背景填充
screen.fill(backgroundcolor)
while True:
for event in pygame.event.get():
#按下关闭按钮,退出程序
if event.type==pygame.QUIT:
sys.exit()
#按下键盘上的任意键,在屏幕上画图
elif event.type == pygame.KEYDOWN:
i = random.randint(0, 2)
drawcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
top = random.randint(0,400)
left = random.randint(0,500)
width = random.randint(0,5)
#画圆
if i == 0:
radiu = random.randint(width,100)
pygame.draw.circle(screen, drawcolor, [top, left], radiu, width)
#画矩形
elif i == 1:
rectwidth = random.randint(0,255)
rectheight = random.randint(0,100)
pygame.draw.rect(screen, drawcolor,[left, top, rectwidth, rectheight], width)
#画椭圆
else:
try:
rectwidth = random.randint(0,255)
rectheight = random.randint(0,100)
pygame.draw.ellipse(screen, drawcolor, [left, top, rectwidth, rectheight], width)
except ValueError:
print 'ellipse'
pass
#重画屏幕
pygame.display.flip()
5、效果图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。