2 回答

TA贡献2080条经验 获得超4个赞
假设您已经在海龟模块中命名了 Screen(),那么您应该将
screen.onscreenclick(whichbox)
代替:
onscreenclick(whichbox)
例子:
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
def ExampleFunction():
return 7
screen.onscreenclick(ExampleFunction)
此外,当 jasonharper 说 onscreenclick() 函数无法返回任何值时,他是正确的。因此,您可以在函数 whichbox() 中包含一个打印函数以打印出一个值,例如:
def whichbox(x,y):
if x<-40 and x>-120:
if y>40 and y<120:
print(1)
return 1
else:
print(0)
return 0
else:
print(0)
return 0
或者,如果您想将打印语句保留在 whichbox() 之外,您还可以执行以下操作:
screen.onscreenclick(lambda x, y: print(whichbox(x, y)))
它创建了一个 lambda 函数,该函数将 (x, y) 从 onscreenclick() 提供给包含 whichbox() 的打印语句。

TA贡献1835条经验 获得超7个赞
这是我在评论中链接到的代码中的一个精简示例。如果您单击一个方块,它将在控制台窗口中打印其编号,从 0 到 8:
from turtle import Turtle, mainloop
CURSOR_SIZE = 20
SQUARE_SIZE = 60
def drawBoard():
for j in range(3):
for i in range(3):
square = Turtle('square', visible=False)
square.shapesize(SQUARE_SIZE / CURSOR_SIZE)
square.fillcolor('white')
square.penup()
square.goto((i - 1) * (SQUARE_SIZE + 2), (j - 1) * (SQUARE_SIZE + 2))
number = j * 3 + i
square.onclick(lambda x, y, number=number: whichsquare(number))
square.showturtle()
def whichsquare(number):
print(number)
drawBoard()
mainloop()
不涉及位置解码——我们让乌龟为我们处理。
添加回答
举报