Pygame實現監聽鼠標示例詳解
pygame如何捕捉鼠標的活動
初始化參數
import pygame, sys from pygame.locals import * def print_text(font, x, y, text, color=(0, 0, 0)): """打印字體函數""" img_text = font.render(text, True, color) screen.blit(img_text, (x, y)) pygame.init() screen = pygame.display.set_mode((400, 400)) pygame.display.set_caption("監聽鼠標活動") while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() screen.fill((255, 255, 255)) pygame.display.update()
鼠標移動
event.type 事件為MOUSEMOTION,則為鼠標移動,event.pos可以獲取當前位置,event.rel鼠標的偏移。
event.type == MOUSEMOTION: event.pos event.rel
我們將位置輸出出來,定義鼠標的位置和鼠標的偏移量
mouse_x = mouse_y = 0 move_x = move_y = 0 print_text(font1, 0, 0, "鼠標事件") print_text(font1, 0, 20, "鼠標的位置:" + str(mouse_x) + "," + str(mouse_y)) print_text(font1, 0, 40, "鼠標的偏移:" + str(move_x) + "," + str(move_y))
鼠標點擊位置
MOUSEBUTTONDOWN和MOUSEBUTTONUP記錄鼠標的按下和放開動作
mouse_down = mouse_up = 0 mouse_down_x = mouse_down_y = 0 mouse_up_x = mouse_up_y = 0
輸出鼠標位置及其對用的按鈕
pygame.mouse.get_pressed() 可以監聽鼠標的三個按鍵。
x, y = pygame.mouse.get_pos() print_text(font1, 0, 180, "鼠標位置:" + str(x) + "," + str(y)) b1, b2, b3 = pygame.mouse.get_pressed() print_text(font1, 0, 200, "按鈕:" + str(b1) + "," + str(b2) + "," + str(b3))
完整代碼
import pygame, sys
from pygame.locals import *
def print_text(font, x, y, text, color=(0, 0, 0)):
"""打印字體函數"""
img_text = font.render(text, True, color)
screen.blit(img_text, (x, y))
pygame.init()
# 字體
font1 = pygame.font.SysFont("方正粗黑宋簡體", 18)
# 鼠標的移動位置
mouse_x = mouse_y = 0
move_x = move_y = 0
mouse_down = mouse_up = 0
mouse_down_x = mouse_down_y = 0
mouse_up_x = mouse_up_y = 0
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("監聽鼠標活動")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, mouse_y = event.rel
elif event.type == MOUSEBUTTONDOWN:
mouse_down = event.button
mouse_down_x, mouse_down_y = event.pos
elif event.type == MOUSEBUTTONUP:
mouse_up = event.button
mouse_up_x, mouse_up_y = event.pos
screen.fill((255, 255, 255))
print_text(font1, 0, 0, "鼠標事件")
print_text(font1, 0, 20, "鼠標的位置:" + str(mouse_x) + "," + str(mouse_y))
print_text(font1, 0, 40, "鼠標的偏移:" + str(move_x) + "," + str(move_y))
print_text(font1, 0, 60, "鼠標按下:" + str(mouse_down)
+ "在" + str(mouse_down_x) + "," + str(mouse_down_y))
print_text(font1, 0, 80, "鼠標松開:" + str(mouse_up)
+ "在" + str(mouse_up_x) + "," + str(mouse_up_y))
x, y = pygame.mouse.get_pos()
print_text(font1, 0, 180, "鼠標位置:" + str(x) + "," + str(y))
b1, b2, b3 = pygame.mouse.get_pressed()
print_text(font1, 0, 200, "按鈕:" + str(b1) + "," + str(b2) + "," + str(b3))
pygame.display.update()
以上就是Pygame實現監聽鼠標示例詳解的詳細內容,更多關於Pygame監聽鼠標的資料請關註WalkonNet其它相關文章!