从 Python Turtle 的 onclick() 获得 2 个位置
Get 2 positions from onclick() of Python Turtle
我正在制作 Tic Tac Toe 游戏,我已经搜索了如何使用 Python Turtle 的 onclick() 获得 2 个位置。我得到的东西就在这个 link 上:
Python 3.0 using turtle.onclick。
我想获得 2 个职位,但我对 "turtle.mainloop()" 有疑问
我的解决方案是:
def getPosX(x_X, y_X):
print("(", x_X, ",", y_X,")")
def getPosO(x_O, y_O):
print("(", x_O, ",", y_O,")"
def choiceX():
Xplay = turtle.getscreen()
Xplay.onclick(getPosX)
turtle.mainloop()
return Xplay
def choiceO():
Oplay = turtle.getscreen()
Oplay.onclick(getPosO)
turtle.mainloop()
return Oplay
我得到的就像它占据了Xplay.onclick()的位置。
而且我还尝试删除每个 def 的“turtle.mainloop()”以在另一个 def 中使用 for 循环:
def play():
for i in range(3):
choiceX()
choiceO()
return i
而且它不起作用。
我想我需要更好的措施
谢谢
我假设您希望乌龟点击在 X 和 O 之间交替,即在 getPosX()
和 getPosO()
之间。我相信你的代码的这种重新排列应该做你想要的:
import turtle
def getPosX(x, y):
print("X: (", x, ",", y, ")")
choiceO()
def getPosO(x, y):
print("O: (", x, ",", y, ")")
choiceX()
def choiceX():
screen.onclick(getPosX)
def choiceO():
screen.onclick(getPosO)
screen = turtle.Screen()
choiceX() # X goes first
turtle.mainloop()
点击屏幕,我得到:
> python3 test.py
X: ( -206.0 , 178.0 )
O: ( 224.0 , 31.0 )
X: ( -14.0 , -122.0 )
O: ( -41.0 , 159.0 )
X: ( 146.0 , 196.0 )
O: ( 105.0 , -70.0 )
X: ( -100.0 , -114.0 )
O: ( -179.0 , 184.0 )
X: ( 23.0 , 137.0 )
当我看到不止一个 mainloop()
调用(或任何 mainloop()
调用不在程序的顶层或最后一件事)时,通常表示对 mainloop()
确实如此。
您设置事件处理程序来执行您想要的操作,然后将程序其余部分的完全控制权交给 mainloop()
。当感兴趣的事件发生时,它将安排调用您的事件处理程序。
我正在制作 Tic Tac Toe 游戏,我已经搜索了如何使用 Python Turtle 的 onclick() 获得 2 个位置。我得到的东西就在这个 link 上: Python 3.0 using turtle.onclick。 我想获得 2 个职位,但我对 "turtle.mainloop()" 有疑问 我的解决方案是:
def getPosX(x_X, y_X):
print("(", x_X, ",", y_X,")")
def getPosO(x_O, y_O):
print("(", x_O, ",", y_O,")"
def choiceX():
Xplay = turtle.getscreen()
Xplay.onclick(getPosX)
turtle.mainloop()
return Xplay
def choiceO():
Oplay = turtle.getscreen()
Oplay.onclick(getPosO)
turtle.mainloop()
return Oplay
我得到的就像它占据了Xplay.onclick()的位置。
而且我还尝试删除每个 def 的“turtle.mainloop()”以在另一个 def 中使用 for 循环:
def play():
for i in range(3):
choiceX()
choiceO()
return i
而且它不起作用。 我想我需要更好的措施 谢谢
我假设您希望乌龟点击在 X 和 O 之间交替,即在 getPosX()
和 getPosO()
之间。我相信你的代码的这种重新排列应该做你想要的:
import turtle
def getPosX(x, y):
print("X: (", x, ",", y, ")")
choiceO()
def getPosO(x, y):
print("O: (", x, ",", y, ")")
choiceX()
def choiceX():
screen.onclick(getPosX)
def choiceO():
screen.onclick(getPosO)
screen = turtle.Screen()
choiceX() # X goes first
turtle.mainloop()
点击屏幕,我得到:
> python3 test.py
X: ( -206.0 , 178.0 )
O: ( 224.0 , 31.0 )
X: ( -14.0 , -122.0 )
O: ( -41.0 , 159.0 )
X: ( 146.0 , 196.0 )
O: ( 105.0 , -70.0 )
X: ( -100.0 , -114.0 )
O: ( -179.0 , 184.0 )
X: ( 23.0 , 137.0 )
当我看到不止一个 mainloop()
调用(或任何 mainloop()
调用不在程序的顶层或最后一件事)时,通常表示对 mainloop()
确实如此。
您设置事件处理程序来执行您想要的操作,然后将程序其余部分的完全控制权交给 mainloop()
。当感兴趣的事件发生时,它将安排调用您的事件处理程序。