文章目录
- 系统内置光标
- 自定义光标
系统内置光标
pygame.mouse中,通过get_cursor和set_cursor来获取和设置光标状态。
pygame中封装了如下常量,表示不同的光标形态
值 | 常量 | 说明 |
---|---|---|
0 | pygame.SYSTEM_CURSOR_ARROW | 箭头 |
1 | pygame.SYSTEM_CURSOR_IBEAM | 插入光标 |
2 | pygame.SYSTEM_CURSOR_WAIT | 等待 |
3 | pygame.SYSTEM_CURSOR_CROSSHAIR | 十字 |
4 | pygame.SYSTEM_CURSOR_WAITARROW | 小型等待 |
5 | pygame.SYSTEM_CURSOR_SIZENWSE | 倾斜双箭头⤡ |
6 | pygame.SYSTEM_CURSOR_SIZENESW | 倾斜双箭头⤢ |
7 | pygame.SYSTEM_CURSOR_SIZEWE | 水平双箭头 |
8 | pygame.SYSTEM_CURSOR_SIZENS | 竖直双箭头 |
9 | pygame.SYSTEM_CURSOR_SIZEALL | 十字箭头 |
10 | pygame.SYSTEM_CURSOR_NO | 禁止标志 |
11 | pygame.SYSTEM_CURSOR_HAND | 抓手 |
下面做一个示例,逐一展示这些光标,其逻辑是,每点击一次,光标的序号加一。
import pygame as pg
pg.init()
screen = pg.display.set_mode([400, 200])
ind = 0
pg.mouse.set_cursor(cursors[ind])
going = True
while going:
pg.time.delay(60)
screen.fill((0, 75, 30))
pg.display.flip()
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
pg.quit()
going = False
if event.type == pg.MOUSEBUTTONDOWN:
ind = (ind+1) % 12
pg.mouse.set_cursor(pg.cursors.Cursor(ind))
效果如下
自定义光标
在上面的示例中,用到了pygame.cursors中的Cursor类,此即光标对象。在pygame.cursors中,除了这个对象,还封装了compile和load_xbm函数,前者用于把字符串编译为光标形状,后者用于加载xbm文件。
下面通过compile和图形来分别创建光标,示例如下
import pygame as pg
pg.init()
screen = pg.display.set_mode([600, 400])
bitmap_1 = pg.cursors.Cursor(*pg.cursors.arrow)
bitmap_2 = pg.cursors.Cursor(
(24, 24), (0, 0), *pg.cursors.compile(pg.cursors.thickarrow_strings)
)
# 通过一个色块来创建光标
surf = pg.Surface((40, 40))
surf.fill((120, 50, 50))
color = pg.cursors.Cursor((20, 20), surf)
cursors = [bitmap_1, bitmap_2, color]
ind = 0
pg.mouse.set_cursor(cursors[ind])
going = True
while going:
pg.time.delay(60)
screen.fill((0, 75, 30))
pg.display.flip()
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
pg.quit()
going = False
if event.type == pg.MOUSEBUTTONDOWN:
ind = (ind+1) % len(cursors)
pg.mouse.set_cursor(cursors[ind])
上述代码中一共设置了三种光标,bitmap1通过cursors中的箭头来生成;其二则通过字符串来编译鼠标形式;其三则直接用一个矩形作为光标。其中thickarrow_strings打印结果如下
>>> import pprint
>>> pprint.pprint(pg.cursors.thickarrow_strings)
('XX ',
'XXX ',
'XXXX ',
'XX.XX ',
'XX..XX ',
'XX...XX ',
'XX....XX ',
'XX.....XX ',
'XX......XX ',
'XX.......XX ',
'XX........XX ',
'XX........XXX ',
'XX......XXXXX ',
'XX.XXX..XX ',
'XXXX XX..XX ',
'XX XX..XX ',
' XX..XX ',
' XX..XX ',
' XX..XX ',
' XXXX ',
' XX ',
' ',
' ',
' ')