доступ к bool из класса в python - PullRequest
0 голосов
/ 07 апреля 2020

Здравствуйте. Как и в заголовке, у меня возникли проблемы с доступом к bool, который создан в классе с именем «InputBox», и в этом классе есть функция с именем «handle_event» и в функции мониторинга текста, если пользователь вводит определенное В строке будет установлено значение bool с именем «Login», равное true. затем в основном l oop затем получит доступ к этому bool в основном l oop и выполнит действия с ним (сейчас я просто хочу его напечатать)

извините, если это глупый вопрос, я относительный новичок и не может заставить что-либо работать

class InputBox:

    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = text
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
            # Change the current color of the input box.
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    Userinput = str(self.text)
                    if Userinput == "tylerodell" or "wxenwxen":
                       #this is where I set the bool named Login to true (first cerated and then set to true)
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                # Re-render the text.
                self.txt_surface = FONT.render(self.text, True, self.color)

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w = width

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect, 2)


#This is all the Text that is used In the Program
TitleScreen_text1 = myfont1.render("Astronomers Notebook", False, (WHITE))
TitleScreen_text2 = myfont2.render("Version 0.1 Alpha", False, (WHITE))
TitleScreen_text3 = myfont2.render("Login To My Notebook", False, (WHITE))
TitleScreen_text4 = myfont2.render("UserName", False, (WHITE))
TitleScreen_text5 = myfont2.render("PassWord", False, (WHITE))

#this is all the varables that the program uses:
#this is for exiting the program
Run = True
#this is for running ceratn parts of the program
TitleScreen = True

#This is the main program:
while Run == True:
    while TitleScreen == True:
        clock = pygame.time.Clock()
        input_box1 = InputBox(500, 400, 140, 32)
        input_box2 = InputBox(500, 500, 140, 32)
        input_boxes = [input_box1, input_box2]
        done = False

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                    Run = False
                    pygame.quit()
                    sys.exit()
                for box in input_boxes:
                    box.handle_event(event)

            for box in input_boxes:
                box.update()

            screen.blit(Night_Sky, (0, 0))
            for box in input_boxes:
                box.draw(screen)

            #this is where I need to accsess the bool "Login"

            #this displays the text
            screen.blit(TitleScreen_text1,(250,200))
            screen.blit(TitleScreen_text2,(15,760))
            screen.blit(TitleScreen_text3,(450,300))
            screen.blit(TitleScreen_text4,(530,365))
            screen.blit(TitleScreen_text5,(530,465))
            pygame.display.flip()
            clock.tick(30)

Заранее спасибо!

также я попытался установить его в качестве глобальной переменной и попробовал первый ответ из здесь

1 Ответ

0 голосов
/ 07 апреля 2020

Если статус входа настраивается независимо для каждого InputBox, вы можете добавить еще один атрибут экземпляра в InputBox, соответствующий login, а затем получить доступ к этому атрибуту в вашем InputBox экземпляре.

В __init__, вам нужно добавить:

self.login = False

Затем в вашем handle_event методе:

if Userinput == "tylerodell" or "wxenwxen":
    #this is where I set the bool named Login to true (first cerated and then set to true)
    self.login = True

Теперь вы можете получить доступ к этому в своем while l oop using:

#this is where I need to accsess the bool "Login"
for box in input_boxes:
    # Do something with login
    print(box.login) # Prints True or False       

В качестве альтернативы, если статус входа в систему распределяется между экземплярами InputBox, т. е. одним глобальным, как вы упомянули, вы можете сделать что-то вроде:

login = False

class InputBox:
    ...

    if Userinput == "tylerodell" or "wxenwxen":
        #this is where I set the bool named Login to true (first cerated and then set to true)
        global login
        login = True

Тогда позже в вашем while l oop вы можете просто print(login) узнать статус.

...