pygame学习教程(六)添加鼠标点击事件

上一篇
在上面的例子实现放置按钮。首先我们优化一下代码
就是这段

    def SetPo(self):  #设置位置 set position  #
        screen.blit(self.mouse_cursor,self.vertex)

screen是在if name == “main”:下定义的

screen = pygame.display.set_mode((640, 480), 0, 32)

这个坏处是很可能定义其它的screen,类似于新的screen
screen1 = pygame.display.set_mode((400, 300), 0, 32)而在我们的类里定义一个self.screen也是不妥的,因为很多情况都是在一个screen下画图,如果每实例化一次继承一个screen是资源的的浪费,所以这里需要加入变量。修改后的代码

 def SetPo(self,objscreen):  #设置位置 set position  #
        objscreen.blit(self.mouse_cursor,self.vertex)```
 def DrawButton(myscreen):
    mylist=[]
    for i in ButtonDict.keys():
        mylist.append("{}.SetPo({})".format(i,myscreen))
    return mylist 

调用的时候需要修改为 s=DrawButton(“screen”)
在这里我们添加鼠标点击事件,思路是获得鼠标点击的(x,y)值看在不在我们的按钮范围内,ButtonDict作为全局变量存储了图标的位置。返回控件的值。代码如下

def AtContr(x,y):
    for mykey in ButtonDict.keys():        
        if x in range(ButtonDict[mykey][0][0],ButtonDict[mykey][1][0]) \
            and  y in range(ButtonDict[mykey][0][1],ButtonDict[mykey][1][1]):
            return mykey

需要在事件控制里加入判断程序,定义自己的_click()处理程序

def butto1_click():
    print("button1鼠标单击")
def butto2_click():
    print("button2鼠标单击") 
MyactiveC=AtContr(x, y)
        for event in pygame.event.get():
            if event.type == QUIT:
                # 接收到退出事件后退出程序
                exit()
            if MyactiveC:
                if event.type == KEYDOWN:
                    print(MyactiveC)
                    print("this is KEYDOWN")
                elif event.type == MOUSEBUTTONDOWN:
                    exec("{}_click()".format(MyactiveC)) # 注意这条可以简化
                elif event.type == MOUSEMOTION:
                    pass
                elif event.type == MOUSEBUTTONUP:
                    pass

完整代码如下

# coding: utf8
import pygame
#导入pygame库
from pygame.locals import *
#导入一些常用的函数和常量
from sys import exit
import  pickle
import DVerctor

ButtonDict={}
class JCon():
    def __init__(self,vertex,mouse_image_filename):
        self.vertex=vertex                         #设置按钮顶点 set button vertex (left,top)格式
        self.mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
        self.count=0                                #用于计数
        self.BoPo =DVerctor.Vec2d(vertex)+DVerctor.Vec2d(self.mouse_cursor.get_width(),self.mouse_cursor.get_height())
        #获得范围left+width,top+height (x,y)+(x1,y1)
    def SetPo(self,objscreen):  #设置位置 set position  #
        objscreen.blit(self.mouse_cursor,self.vertex)
    def SetPoMuoseup(self,newPlace:tuple):
        self.vertex=newPlace

class Jbutton(JCon):
    pass
def TextPygame():  #测试模块是否存在和版本号
    print(pygame.ver)
    pgname = ['pygame.cdrom', 'pygame.cursors', 'pygame.display', 'pygame.draw',
              'pygame.event', 'pygame.font', 'pygame.image', 'pygame.joystick',
              'pygame.key', 'pygame.mixer', 'pygame.mouse', 'pygame.movie', 'pygame.music',
              'pygame.overlay', 'pygame', 'pygame.rect', 'pygame.sndarray', 'pygame.sprite',
              'pygame.surface', 'pygame.surfarray', 'pygame.time']
    for i in pgname:
        if i is None:
            print(i+" is None")
        else:
            print(i + " at this computer")

def storeTree(filename,*args):
    with open(filename,'wb') as fw:  #打开需要用'wb'
        for i in args:
            pickle.dump(i, fw,-1) #为了保护数据protocol=-1,设为0可以看到数据

def grabTree(filename):
    Mylist=[]   #返回变量的列表
    with open(filename,'rb') as fr:
        while True:        #这里用try最简单,不用定义循环次数
            try:
                Mylist.append(pickle.load(fr))
            except:
                break
    return Mylist

def CreateButton():
   # global ButtonDict
    mylist=[]
    for exi in ButtonDict.keys():
        mylist.append("{}=Jbutton({},'{}')".format(exi,ButtonDict[exi][0],ButtonDict[exi][1]))
    for exi in ButtonDict.keys():
        mylist.append('ButtonDict["{0}"] = [ButtonDict["{0}"][0],({0}.BoPo[0],{0}.BoPo[1])]'.format(exi))
    return mylist

def DrawButton(myscreen):
    mylist=[]
    for i in ButtonDict.keys():
        mylist.append("{}.SetPo({})".format(i,myscreen))
    return mylist

def RunStr(s:list):
    for i in s:
        exec(i)

#ButtonDict = {'butto1': [(12, 13), (112, 49)], 'butto2': [(52, 73), (152, 109)]}
def AtContr(x,y):
    for mykey in ButtonDict.keys():       
        if x in range(ButtonDict[mykey][0][0],ButtonDict[mykey][1][0]) \
            and  y in range(ButtonDict[mykey][0][1],ButtonDict[mykey][1][1]):
            return mykey

def butto1_click():
    print("button1鼠标单击")
def butto2_click():
    print("button2鼠标单击")
if __name__ == "__main__":
    background_image_filename = 'sushiplate.jpg'
    # 指定图像文件名称
    pygame.init()
    # 初始化pygame,为使用硬件做准备
    screen = pygame.display.set_mode((640, 480), 0, 32)
    # 创建了一个窗口
    pygame.display.set_caption("Hello, World!")    # 设置窗口标题
    background = pygame.image.load(background_image_filename).convert()
    #在这里添加按钮
    ButtonDict["butto1"] = [(12, 13), 'feid1.png']  #全局变量,判定
    ButtonDict["butto2"] = [(52, 73), 'feid1.png']
    s=CreateButton()
  #  RunStr(s) 这里不能调用函数
    for i in s:
        exec(i)
    print("ButtonDict=",ButtonDict)
    #修改ButtonDict
    while True:
        # 游戏主循环
        x, y = pygame.mouse.get_pos()
        # 获得鼠标位置
        # 计算光标的左上角位置
        #看x,y是否在控件位置上
        MyactiveC=AtContr(x, y)
        for event in pygame.event.get():
            if event.type == QUIT:
                # 接收到退出事件后退出程序
                exit()
            if MyactiveC:
                if event.type == KEYDOWN:
                    print(MyactiveC)
                    print("this is KEYDOWN")
                elif event.type == MOUSEBUTTONDOWN:
                    exec("{}_click()".format(MyactiveC))
                elif event.type == MOUSEMOTION:
                    pass
                elif event.type == MOUSEBUTTONUP:
                    pass
        screen.blit(background, (0, 0))        # 将背景图画上去
        # 把光标画上去
        s=DrawButton("screen")
        for i in s:
            exec(i)
        pygame.display.update()
        # 刷新一下画面

点击图标输出:
button2鼠标单击
button1鼠标单击
[下一篇]

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值