python学习之GUI(pygame鼠

2023-01-31 02:01:51 python pygame 学习

鼠标的位置和其他PyGame的程序一样使用坐标来表示。坐标的值经常使用x和y变量来表示。左上角的坐标值是0,0,x和y的值随着鼠标的向右和向下的移动而增加。


打印鼠标左键点击位置

import pygame
pygame.init()

windowsize=[400,300]
screen=pygame.display.set_mode(windowSize)
clock=pygame.time.Clock()

done=False

while not done:
    for event in pygame.event.get():
        if event.type==pygame.MOUSEBUTTONDOWN:
            pos=pygame.mouse.get_pos()
            print pos
        if event.type==pygame.QUIT:
            done=True
pygame.quit()

通过点击矩形内改变背景颜色

import pygame
pygame.init()

windowSize=[400,300]
screen=pygame.display.set_mode(windowSize)
clock=pygame.time.Clock()
black=pygame.color.Color("#000000")
white=pygame.color.Color("#FFFFFF")
btnColour=pygame.color.Color("#A45C8F")

btnWidth=50
btnLength=20
btnX=(windowSize[0]-btnWidth)/2
btnY=(windowSize[1]-btnLength)/2

toggled=False
pos=(0,0)
done=False
while not done:
    if toggled:
        screen.fill(black)
    else:
        screen.fill(white)

    pygame.draw.rect(screen,btnColour,[btnX,btnY,btnWidth,btnLength])
    if btnX<=pos[0]<=btnX+btnWidth and btnY<=pos[1]<=btnY+btnLength:
        toggled=not toggled
        pos=[0,0]

    for event in pygame.event.get():
        if event.type==pygame.MOUSEBUTTONDOWN:
            pos=pygame.mouse.get_pos()
        if event.type==pygame.QUIT:
            done=True
    pygame.display.flip()
    clock.tick(10)
pygame.quit()


相关文章