这个物体是从哪里来的

2024-10-04 11:35:00 发布

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

我是一个比较新的程序员,我正在制作一个游戏。我正在使用我以前的项目运行良好的一些代码。但是现在当我尝试调用某个函数时,我认为它不需要任何参数,它会返回一些奇怪的错误。你知道吗

我从以前的项目中复制了这个类:

import pyglet as p


class Button(object):
    def __init__(self, image, x, y, text, on_clicked):
        self._width = image.width
        self._height = image.height
        self._sprite = p.sprite.Sprite(image, x, y)
        self._label = p.text.Label(text,
                                  font_name='Times New Roman',
                                  font_size=20,
                                  x=x + 20, y=y + 15,
                                  anchor_x='center',
                                  anchor_y='center')
        self._on_clicked = on_clicked  # action executed when button is clicked

    def contains(self, x, y):
        return (x >= self._sprite.x - self._width // 2
            and x < self._sprite.x + self._width // 2
            and y >= self._sprite.y - self._height // 2
            and y < self._sprite.y + self._height // 2)

    def clicked(self, x, y):
        if self.contains(x, y):
            self._on_clicked(self)

    def draw(self):
        self._sprite.draw()
        self._label.draw()

我有调用函数的窗口事件(w是窗口):

@w.event
def on_mouse_press(x, y, button, modifiers):
    for button in tiles:
        button.clicked(x, y)

它调用的函数有三种变体,每种变体都有不同的“错误”:

def phfunc(a):
    print(a)

返回以下内容:<Button.Button object at 0x0707C350>

def phfunc(a):
    print('a')

退货:a 实际上应该是这样的

def phfunc():
    print('a')

返回导致以下情况的回调的长列表:

  File "C:\Google Drive\game programmeren\main.py", line 15, in on_mouse_press
    button.clicked(x, y)
  File "C:\Google Drive\game programmeren\Button.py", line 25, in clicked
    self._on_clicked(self)
TypeError: phfunc() takes no arguments (1 given)

我最好的猜测是,它的论点是来自Button类的self。这是正确的,我应该担心吗?你知道吗


Tags: andtextinimageselfondefbutton
1条回答
网友
1楼 · 发布于 2024-10-04 11:35:00

使用self作为参数调用存储在self._on_clicked中的函数引用。selfButton类的实例:

self._on_clicked(self)

自定义Button类的默认表示形式是<Button.Button object at 0x0707C350>。你知道吗

既然你这么做了,那就不用担心了。你知道吗

相关问题 更多 >