【问题标题】:Get 2 positions from onclick() of Python Turtle从 Python Turtle 的 onclick() 获取 2 个位置
【发布时间】:2017-05-13 07:12:20
【问题描述】:

我正在制作井字游戏,我已经在寻找如何使用 Python Turtle 的 onclick() 获得 2 个位置。我得到的东西就在这个链接上: 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

它不起作用。 我想我需要更好的衡量标准 谢谢

【问题讨论】:

    标签: python turtle-graphics


    【解决方案1】:

    我假设您希望您的海龟点击在 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() 以完成程序的其余部分。当感兴趣的事件发生时,它将安排您的事件处理程序被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-29
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多