You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Turtle赛跑程序onscreenclick报错:raceRound()需0参数却传入2个

Fixing the TypeError in Your Turtle Race Program

Ah, I’ve run into this exact quirk with Turtle’s onscreenclick before—let’s break down what’s going wrong and fix it quickly.

The Root Cause

When you call onscreenclick(raceRound), Turtle automatically passes two positional arguments to your callback function: the X and Y coordinates of where the screen was clicked. But your raceRound() function is defined to take 0 arguments, hence the error: "raceRound() takes 0 positional arguments but 2 were given".

Two Simple Solutions

1. Update raceRound to Accept the Coordinates (Even If You Don’t Use Them)

Just add two parameters to your function—you can name them anything (like x and y) and ignore them if you don’t need the click position for your race logic:

import turtle
import random

# Set up your race environment
screen = turtle.Screen()
screen.setup(width=500, height=400)

# Create and position your turtles
turtle1 = turtle.Turtle(shape="turtle")
turtle1.penup()
turtle1.goto(-230, 50)

turtle2 = turtle.Turtle(shape="turtle")
turtle2.penup()
turtle2.goto(-230, -50)

def raceRound(x, y):  # Added x and y parameters to match Turtle's callback requirement
    # Move each turtle a random distance
    turtle1.forward(random.randint(10, 30))
    turtle2.forward(random.randint(10, 30))
    
    # Check for a winner
    if turtle1.xcor() >= 230:  # Adjust based on your finish line position
        print("Turtle 1 takes the win!")
        screen.onscreenclick(None)  # Stop listening for clicks once race ends
    elif turtle2.xcor() >= 230:
        print("Turtle 2 is the champion!")
        screen.onscreenclick(None)

# Bind the click event to your updated function
screen.onscreenclick(raceRound)
screen.mainloop()

2. Use a Lambda to Wrap the Function (If You Want to Keep raceRound Parameter-Free)

If you prefer to leave raceRound as a 0-argument function, use a lambda to absorb the extra coordinates Turtle sends:

# Keep your original raceRound definition
def raceRound():
    turtle1.forward(random.randint(10, 30))
    turtle2.forward(random.randint(10, 30))
    
    if turtle1.xcor() >= 230:
        print("Turtle 1 wins!")
        screen.onscreenclick(None)
    elif turtle2.xcor() >= 230:
        print("Turtle 2 wins!")
        screen.onscreenclick(None)

# Use lambda to pass the click event without modifying raceRound
screen.onscreenclick(lambda x, y: raceRound())

A Quick Quality-of-Life Touch

I added screen.onscreenclick(None) in the winner check—this stops the program from listening for clicks once a winner is declared, so users can’t keep moving turtles after the race ends.

内容的提问来源于stack exchange,提问作者Nicholas Norris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:13:10