介绍
Pygame实现监听鼠标的示例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
初始化参数
import Pygame,系统 得到pygame.locals import * def print_text(字体,,x,, y,,文字,颜色=(0,0,0)): ,,,“““打印字体函数“““ ,,,img_text =, font.render(文本,,真的,,颜色) ,,,screen.blit (img_text,, (x, y)) pygame.init () 时间=screen pygame.display.set_mode ((400,, 400)) pygame.display.set_caption(“监听鼠标活动“) while 真正的: ,,,for event 拷贝pygame.event.get (): ,,,,,,,if event.type ==,退出: ,,,,,,,,,,,pygame.quit () ,,,,,,,,,,,sys.exit () ,,,screen.fill ((255,, 255,, 255)) ,,,pygame.display.update ()
鼠标移动
事件。种事件为MOUSEMOTION,则为鼠标移动,event.pos可以获取当前位置,事件。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,系统 得到pygame.locals import * def print_text(字体,,x,, y,,文字,颜色=(0,0,0)): ,,,“““打印字体函数“““ ,,,img_text =, font.render(文本,,真的,,颜色) ,,,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 真正的: ,,,for event 拷贝pygame.event.get (): ,,,,,,,if event.type ==,退出: ,,,,,,,,,,,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 null null null null null null null null null null null null null null null null null nullPygame实现监听鼠标的示例分析