Ошибка с объектом Pygame не повторяется

1
#campaign module for blunt wars
import pygame
import time
import sys

pygame.init()

size = [400, 400]
width = size[0]
height = size[1]

#colors
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
blue = (0,0,255)
bright_red = (255,0,0)
bright_green = (0,255,0)
#end colors

screen = pygame.display.set_mode((size), pygame.RESIZABLE)
pygame.display.set_caption('Blunt Wars - Campaign')
clock = pygame.time.Clock()

#updates screen res
for event in pygame.event.get():
    if event.type ==pygame.VIDEORESIZE:
        screen = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)

text = pygame.font.SysFont('Arial', 30)

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+y > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic,(x,y,w,h))
        smallText = pygame.font.Sysfont('Arial',20)
        textSurf, TextRect = text_objects(msg, smallText)
        textRect.center = ( (x+(w/2)), (y+(h/2)) )
        screen.blit(textSurf, TextRect)

def intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            #print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
                #import Blunt_Wars

        screen.fill(blue)
        header = pygame.font.SysFont('Arial',115)
        textSurf, textRect = text_objects("Blunt Wars - Campaign", header)
        textRect.center = ((width/2),(height/2))
        screen.blit(textSurf, textRect)

        button("Start New",400,450,100,50,green,bright_green,game_loop)

        pygame.display.update()
        clock.tick(15)

def game_loop():
    print("game loop ran")
    pygame.quit()
    quit()


intro()

Так что это моя вся программа и я пытаюсь сделать главное меню, но когда я запускаю этот код, я получаю эту ошибку:

textSurf, textRect = text_objects("Blunt Wars - Campaign", header)
TypeError: 'pygame.Surface' object is not iterable.

Я не понимаю, почему это делается, но если кто-то может мне помочь, это будет очень признательно.

  • 1
    Возможный дубликат Python: TypeError: объект 'NoneType' не повторяется
  • 0
    type (pygame.Surface) =?
Показать ещё 1 комментарий
Теги:
python-3.x
pygame

2 ответа

3
Лучший ответ

text_objects функция возвращает pygame.Surface, но вы пытаетесь распаковать эту поверхность в переменные textSurf, TextRect в button функции и так как pygame.Surface не итерация, то TypeError получает поднятые:

textSurf, TextRect = text_objects(msg, smallText)

Чтобы исправить ошибку, вы можете создать textRect с pygame.Surface.get_rect метода text_objects функции text_objects и вернуть поверхность и rect как кортеж. Затем вы можете распаковать этот кортеж в функции button:

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    # Create the text rect.
    textRect = textSurface.get_rect()
    # Return a tuple consisting of the surface and the rect.
    return textSurface, textRect

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+y > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic,(x,y,w,h))
        smallText = pygame.font.SysFont('Arial',20)  # Typo: Sysfont -> SysFont
        textSurf, textRect = text_objects(msg, smallText)  # Typo: TextRect -> textRect
        textRect.center = ( (x+(w/2)), (y+(h/2)) )
        screen.blit(textSurf, textRect)  # Typo: TextRect -> textRect

Я также исправил некоторые опечатки.

Кстати, я рекомендую создавать объекты шрифтов один раз в глобальной области и затем повторно использовать их в остальной части программы по соображениям эффективности (этот smallText = pygame.font.SysFont('Arial',20) должен быть в глобальном объем).

1

Посмотрите на это:

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface

textSurf, textRect = text_objects("Blunt Wars - Campaign", header)

text_objects() возвращает результат font.render() который является экземпляром pygame.Surface.

Это не повторяется и почему ваша распаковка не работает...

Ещё вопросы

Сообщество Overcoder
Наверх
Меню