python中的pygame模块使用方法_python中pygame模块用法实例

import pygame, sys

from pygame.locals import *

#set up pygame

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)

pygame.display.set_caption("hello, world")

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

basicFont = pygame.font.SysFont(None, 48)

text = basicFont.render("Hello ,world", True, WHITE, BLUE)

textRect = text.get_rect()

textRect.centerx = windowSurface.get_rect().centerx

textRect.centery = windowSurface.get_rect().centery

windowSurface.fill(WHITE)

pygame.draw.polygon(windowSurface, GREEN, ((146, 0),

(291, 106), (236, 277), (56, 277), (0, 106)))

pygame.draw.line(windowSurface, BLUE, (60, 60), (120,

60), 4)

pygame.draw.line(windowSurface, BLUE, (120, 60), (60,

120))

pygame.draw.line(windowSurface, BLUE, (60, 120), (120,

120), 4)

pygame.draw.circle(windowSurface, BLUE, (300, 50), 20, 0)

pygame.draw.ellipse(windowSurface, RED, (300, 250, 40,

80), 1)

pygame.draw.rect(windowSurface, RED, (textRect.left - 20,

textRect.top - 20, textRect.width + 40, textRect.height + 40))

pixArray = pygame.PixelArray(windowSurface)

pixArray[480][380] = BLACK

del pixArray

windowSurface.blit(text, textRect)

pygame.display.update()

while True:

for event in pygame.event.get():

if event.type == QUIT:

pygame.quit()

sys.exit()

运行后打出的图片如下:

2014109103540028.png?20149910366

希望本文所述对大家的Python程序设计有所帮助。

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
感谢你的提问!在pythonpygame模块下创建窗口并添加按钮可以使用pygame的Sprite类和Rect类。具体步骤如下: 1.导入pygame和sys模块: ``` import pygame import sys ``` 2.初始化pygame: ``` pygame.init() ``` 3.设置窗口大小和标题: ``` size = [800, 600] # 窗口大小 screen = pygame.display.set_mode(size) # 创建窗口 pygame.display.set_caption("My Game") # 设置窗口标题 ``` 4.定义一个按钮类Button,继承自pygame的Sprite类: ``` class Button(pygame.sprite.Sprite): def __init__(self, color, x, y, width, height): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y ``` 其,color是按钮的颜色,x和y是按钮的位置坐标,width和height是按钮的尺寸。 5.创建一个按钮实例: ``` button = Button((255, 0, 0), 300, 200, 200, 100) ``` 其,(255, 0, 0)是按钮的颜色,300和200是按钮的位置坐标,200和100是按钮的尺寸。 6.将按钮添加到精灵组: ``` buttons = pygame.sprite.Group() buttons.add(button) ``` 7.在游戏循环处理事件,并在窗口绘制按钮: ``` while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill((255, 255, 255)) # 填充窗口背景色 buttons.draw(screen) # 绘制按钮 pygame.display.update() ``` 注意,buttons.draw(screen)用于将按钮绘制到窗口。 以上就是在pythonpygame模块下创建窗口添加按钮的方法,希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值