python中的python单击事件范围问题

时间:2011-02-18 02:30:25

标签: python scope mouseevent pygame

我使用python pygame库创建了一个GameObject类,它在屏幕上绘制一个矩形。    我想集成一个事件处理程序,它允许我绘制矩形,但GameObject的点击事件没有注册。 以下是该类代码的几段代码:

def on_event(self, event):

    if event.type == pygame.MOUSEBUTTONDOWN:
        print "I'm a mousedown event!"
        self.down = True
        self.prev_x=pygame.mouse.get_pos(0)
        self.prev_y=pygame.mouse.get_pos(1)

    elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
        self.down = False

def on_draw(self, surface):

    #paints the rectangle the particular color of the square
    pygame.draw.rect(surface, pygame.Color(self.red, self.green, self.blue), self.geom)`

我是否需要将rect设置为图像以便注册鼠标事件,还是有其他方法可以拖动此框?

1 个答案:

答案 0 :(得分:1)

  
    

我是否需要将rect设置为图像以便注册鼠标事件,还是有其他方法可以拖动此框?

  

无需图片。解决方案:

注意:

  1. 您已经使用event来获取MOUSEMOTION,因此请使用事件的事件数据:.pos和.button。

  2. 使用Color类作为单个变量存储:

    self.color_bg =颜色(“蓝色”) self.color_fg =颜色(20,20,20) print self.color_bg.r,self.color_bg.g,self.color_bg.b

  3. 注意:我保留了一些稍微冗长的代码以便于阅读,例如:你可以这样做:

    # it uses
    x,y = event.pos
    if b.rect.collidepoint( (x,y) ):
    # you could do (the same thing)
    if b.rect.collidepoint( event.pos* ):
    

    解决方案:

    import pygame
    from pygame.locals import *
    from random import randint
    
    class Box(object):
        """simple box, draws rect and Color"""
        def __init__(self, rect, color):
            self.rect = rect
            self.color = color
        def draw(self, surface):
            pygame.draw.rect(surface, self.color, self.rect)
    
        class Game(object):
        def __init__(self):
            # random loc and size boxes
            # target = box to move
            self.target = None
    
            for i in range(5):
                x,y = randint(0, self.width), randint(0, self.height)
                size = randint(20, 200)
    
                r = Rect(0,0,0,0)
                # used 0 because: will be using propery, but have to create it first
                r.size = (size, size)
                r.center = (x, y)
                self.boxes.append( Box(r, Color("red") ))
    
        def draw(self):
            for b in self.boxes: b.draw()
    
        def on_event(self, event):
            # see: http://www.pygame.org/docs/ref/event.html
    
            if event.type == MOUSEBUTTONDOWN and event.button = 1:
                # LMB down = target if collide
                x,y = event.pos
                for b in self.boxes:
                    if b.rect.collidepoint( (x,y) ): self.target = b
    
            elif event.type == MOUSEBUTTONUP and event.button = 1:
                # LMB up : untarget
                self.target = None
    
            elif event.type == MOUSEMOTION:
                x,y = event.pos
                # is a valid Box selected?
                if self.target is not None:
                    self.target.rect.center = (x,y)