Kookerus
Kookerus

Reputation: 536

How To Find Out If A .Rect() Has Been Clicked In Pygame

I'm trying to find out if a user has clicked on a .rect(). I've read a bunch of tutorials, but I'm still running into problems. I have two files: One that is the main python file, and one that defines the .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)))

The error I get is AttributeError: 'TextBox' object has no attribute 'rect' How do I solve this?

Upvotes: 1

Views: 854

Answers (1)

user2746752
user2746752

Reputation: 1088

You're TextBox class doesn't have a rect. Add this somewhere at the bottom of the __init__ method of the TextBox class:

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

Do the same in the update method.

Upvotes: 1

Related Questions