如何确定在Pygam中是否单击了.Rect()

2024-04-26 14:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道用户是否点击了.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' 我怎么解决这个问题?在


Tags: 文件rectimportselfeventsizedisplayposition
1条回答
网友
1楼 · 发布于 2024-04-26 14:23:49

你的TextBox类没有rect。在TextBox类的__init__方法的底部添加以下内容:

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

在update方法中执行相同的操作。在

相关问题 更多 >