__init__() 得到了一个意外的关键字参数“text”

use*_*363 6 python livewires python-3.x

我一直在使用 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()
Run Code Online (Sandbox Code Playgroud)

但是,当我运行这个程序时出现错误(见下文)

  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'
Run Code Online (Sandbox Code Playgroud)

我希望你能帮忙

dan*_*som 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)
        .........
Run Code Online (Sandbox Code Playgroud)

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

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

games.Text(my_screen, 500, 30, "Score: 1756521", 50, color.black)
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

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