__init __()得到了一个意外的关键字参数'text'

时间:2014-03-03 15:01:28

标签: python python-3.x livewires

我使用Python 3.3.1编写了Python for Absolute Beginners一书。

我正在尝试使用以下代码将文本添加到屏幕。我需要继续使用Python 3.3.1,但我认为本书中的代码适用于Python 2.X。

from livewires import games, color

class Pizza(games.Sprite):
    """A falling pizza"""
    def __init__(self, screen, x,y, image, dx, dy):
        """Initialise pizza object"""
        self.init_sprite(screen = screen, x = x, y = y, image = image, dx = dx, dy = dy)

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

#main

my_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT)

wall_image = games.load_image("wall.jpg", transparent = False)
pizza_image = games.load_image("pizza.jpg")
my_screen.set_background(wall_image)
games.Text(screen = my_screen, x = 500, y = 30, text = "Score: 1756521", size = 50, color = 

my_screen.mainloop()

然而,当我运行这个程序时,我收到一个错误(见下文)

  games.Text(screen = my_screen, x = 500, y = 30, text = "Score: 1756521", size = 50, color = color.black)
TypeError: __init__() got an unexpected keyword argument 'text'

我希望你能帮忙

1 个答案:

答案 0 :(得分:1)

我回复了评论,但我想我会详细说明一遍。

我刚刚查看了livewires games.py模块的源代码,如我所知

class Text(Object, ColourMixin):
    """
    A class for representing text on the screen.

    The reference point of a Text object is the centre of its bounding box.
    """

    def __init__(self, screen, x, y, text, size, colour, static=0):
        self.init_text (screen, x, y, text, size, colour, static)
        .........

正如您所看到的,Text类的__init__()不期望名为text的关键字参数。相反,它期望一系列位置参数。

所以你的代码应该是这样的

games.Text(my_screen, 500, 30, "Score: 1756521", 50, color.black)

修改

如2rs2ts所述,如果指定了所有参数名称,则可以为位置参数提供关键字参数。但是,由于您使用了关键字颜色而不是颜色,因此您的代码失败了。所以以下内容也应该有效(但我建议使用位置参数)

games.Text(screen=my_screen, x=500, y=30, text="Score: 1756521", size=50, colour=color.black)

根据PEP8,您还应注意 - “当用于指示关键字参数或默认参数值时,请勿在=符号周围使用空格。”