如何在Pygame中点击.Rect()

时间:2014-10-23 05:10:22

标签: python python-3.x click pygame

我试图找出用户是否点击了.rect()。我已经阅读了很多教程,但我仍遇到问题。我有两个文件:一个是主要的python文件,另一个是定义.rect()。

#main.py
import pygame,os,TextBox
from pygame.locals import *

pygame.init()

myTextBox = TextBox.TextBox()

WHITE = (255, 255, 255)

size = (400, 200)
screen = pygame.display.set_mode(size)

done = False

boxes = [myTextBox]

while not done:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True
        elif event.type == MOUSEMOTION: x,y = event.pos
        for box in boxes:
                if myTextBox.rect.collidepoint(x,y): print ('yay')



    screen.fill(WHITE)
    myTextBox.display(screen, 150, 150, 20, 100)

    pygame.display.flip()

pygame.quit()


#TextBox.py
import pygame
from pygame.locals import *

class TextBox:
    def __init__(self):
        self.position_x = 100
        self.position_y = 100
        self.size_height = 10
        self.size_width = 50
        self.outline_color = (  0,   0,   0)
        self.inner_color   = (255, 255, 255)

    def display(self, screen, x, y, height, width):
        self.position_x = x
        self.position_y = y
        self.size_height = height
        self.size_width = width

        pygame.draw.rect(screen, self.outline_color, Rect((self.position_x - 1, self.position_y - 1, self.size_width + 2, self.size_height + 2)))
        pygame.draw.rect(screen, self.inner_color, Rect((self.position_x, self.position_y, self.size_width, self.size_height)))

我得到的错误是AttributeError: 'TextBox' object has no attribute 'rect' 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你的TextBox类没有矩形。将它添加到TextBox类的__init__方法的底部:

self.rect = pygame.Rect(self.position_x,self.position_y,self.size_width,self.size_height)

在更新方法中执行相同操作。