TypeError: clicking() takes exactly 0 arguments (2 given)

TypeError: clicking() takes exactly 0 arguments (2 given)

我正在尝试创建一个简单的答题器风格的游戏。但是最近我遇到了一些问题。在我之前的一个问题中,我问过如何解决 screen = getscreen() 错误。这个问题得到了回答,但同一天我得到了一个新的错误。

当我尝试单击按钮时,我收到此回溯错误:

TypeError: clicking() takes exactly 0 arguments (2 given) at <unknown>`. 

它链接回 clicking() 的定义。

定义clicking()的部分代码:

def clicking():
  if distance( button.pos() ) < 2:
    BUTTON_CLICKS = BUTTON_CLICKS + 1

全部代码:

import time
import turtle

screen = turtle.Screen()
image_BUTTON = "Button.png"
image_BUTTON_CLICKS = "Button_clicks.png"
image_UPGRADEBG = "UPGRADEBG.png"

button = turtle.Turtle()
BUTTON_CLICKS = 0
BUTTON_CLICKS1 = turtle.Turtle()
BUTTON_CLICKS2 = turtle.Turtle()
upgrade = turtle.Turtle()
upgrade1 = turtle.Turtle()
upgrade2 = turtle.Turtle()
upgrade3 = turtle.Turtle()
upgrade4 = turtle.Turtle()
upgrade5 = turtle.Turtle()

screen.addshape(image_BUTTON)
button.penup()
button.speed(0)
button.left(90)
button.shape(image_BUTTON)
button.goto(0, 0)

BUTTON_CLICKS1.speed(0)
BUTTON_CLICKS1.penup()
BUTTON_CLICKS1.hideturtle()
BUTTON_CLICKS1.goto(-65, 170)
BUTTON_CLICKS1.write("Button   clicks: %d" % BUTTON_CLICKS, font=("Bebas", 14, "bold"))

upgrade.speed(0)
upgrade.penup()
upgrade.hideturtle()
upgrade.goto(110, -190)
upgrade.write("Upgrades", font=("Bebas", 13, "bold"))

def clicking():
  if distance( button.pos() ) < 2:
    BUTTON_CLICKS = BUTTON_CLICKS + 1

screen = turtle.getscreen()
screen.onclick( clicking )

注意:我正在 trinket.io

制作这款游戏

onclick 接受一个函数作为参数并使用另外两个参数调用它,即单击点的坐标。

From the documentation:

turtle.onclick(fun, btn=1, add=None)¶

Parameters: fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

(强调我的)

因此,当您提供 不接受任何参数的函数 (clicking()) 时 ,将引发 TypeError因为 onclick 会用两个参数调用它。

向您的函数添加两个参数以删除 TypeError,您如何处理这些由您决定。

def clicking(x, y):
  if distance( button.pos() ) < 2:
    BUTTON_CLICKS = BUTTON_CLICKS + 1

引用 official docs(强调我的):

turtle.onclick(fun, btn=1, add=None)

Parameters:

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

num – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True, a new binding will be added, otherwise it will replace a former binding Bind fun to mouse-click events on this turtle.

您的函数有 0 个参数,文档指定它应该正好接受两个参数。

将您的函数签名更改为:

def clicking(x, y):
    pass  # your code goes here