Help me with turtle onclick func

could you tell me why the onclick doesnt work, but onkeypress is working

Code
import turtle
import random
import time

# Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.tracer(0)
wn.screensize(400, 400)

# Objects
dot = turtle.Turtle()
dot.speed(0)
dot.shape("circle")
dot.shapesize(0.5 , 0.5)
dot.color("white")
dot.pendown()
dot.goto(random.randint(-190, 190) , random.randint(-190, 190))

# Function
def randomDot():
    x = random.randint(-190, 190)
    y = random.randint(-190, 190)
    dot.goto(x , y)


wn.listen()
wn.onclick(randomDot, btn = 1)
wn.onkeypress(randomDot, "Up")

# Main Loop
while True:
    wn.update()
    time.sleep(1 / 60)
    
    
wn.mainloop()
Error messages after I clicked the screen

Exception in Tkinter callback
Traceback (most recent call last):
File “C:\Users\Andy\AppData\Local\Programs\Thonny\lib\tkinter_init_.py”, line 1705, in call
return self.func(*args)
File “C:\Users\Andy\AppData\Local\Programs\Thonny\lib\turtle.py”, line 675, in eventfun
fun(x, y)
TypeError: randomDot() takes 0 positional arguments but 2 were given

Hi there!

Turtle’s onclick function gives the specified function (randomDot) two parameters: the x and y positions of the mouse.

Your function randomDot doesn’t take any parameters, but turtle’s onclick is trying to give that function the parameters mentioned above.

The reason why onkeypress is working while onclick is not is because turtle’s onkeypress function does not give any parameters to the randomDot function.

Even though the x and y values given by onclick don’t have any use for your function, randomDot still needs to accept those values given by onclick.

The solution here would just be to add x and y arguments to the randomDot function (and never use the x and y), but since onkeypress gives no parameters, another error will appear saying
randomDot() takes 2 positional arguments but 0 were given

The solution:
We want the function randomDot to accept the x and y positions of the mouse from onclick, but we also don’t want randomDot to raise an error when it demands an x and y from onkeypress (which doesn’t give anything to randomDot).

The solution is to make randomDot’s arguments like so:
def randomDot(x=0, y=0):
This allows randomDot to accept two values if they are given, but randomDot just sets those values to 0 if no values are given.

Feel free to message me if you have any questions.

Cheers!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.