2016-01-20 110 views
0

我正在嘗試創建一個簡單的答題器式遊戲。但最近我遇到了一些問題。在我之前的一個問題中,我問如何解決screen = getscreen()錯誤。這個問題得到了回答,但同一天我得到了一個新的錯誤。TypeError:點擊()只需要0個參數(給出2個)

當我嘗試按一下按鈕我得到這個錯誤回溯:

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

回答

1

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 
+0

哈,我沒有得到這個錯誤了。但是我得到'NameError:name'distance'沒有在第41行定義。 (對不起,我很害怕)我很明顯錯過了什麼? – righteous

+0

你還沒有定義'distance',爲什麼要在那裏添加它? –

+0

我正在通過互聯網課程學習。在那裏的例子中我沒有看到一個定義。所以我認爲我不需要一個。我如何定義它? – righteous

0

報價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