代码之家  ›  专栏  ›  技术社区  ›  Vaibhav Saini

为什么onscreenclick()和mainloop()之间的语句不能执行?

  •  1
  • Vaibhav Saini  · 技术社区  · 7 年前

    我试图打印一个变量的值,该变量的值是根据turtle中点击点的坐标赋值的。

    import turtle as t
    position=0
    j=0
    def get(a,b):
        print("(", a, "," ,b,")")
        global position
        if b>0:
            if a<0:
                position=1
            else:
                position=2
        else:
            if a<0:
                position=3
            else:
                position=4
    
    def main():
        global j
        j = j+1
        t.onscreenclick(get)
        print(position)
        t.mainloop()
    
    main()
    

    但是在这两个函数之间什么都没有(我尝试了调用其他函数等其他事情) t.onscreenclick() t.mainloop() 被执行?

    1 回复  |  直到 7 年前
        1
  •  0
  •   furas    7 年前

    onscreenclick 不用等待你的点击。它只通知 mainloop 单击时必须执行的功能。 主回路 做所有事情-它创建主窗口,从操作系统获取鼠标/键盘事件,将事件发送到窗口中的元素/小部件,运行分配给 屏幕点击 / ontimer /等等,在屏幕上重画元素等等。

    所以 print(position) 在偶数之前执行 主回路 打开窗口。
    你必须在里面打印 get()

    import turtle as t
    
    # --- functions ---
    
    def get(x, y):
    
        print("(", x, ",", y, ")")
    
        if y > 0:
            if x < 0:
                position = 1
            else:
                position = 2
        else:
            if x < 0:
                position = 3
            else:
                position = 4
    
        print('pos:', position)
    
    # --- main ---
    
    # inform mainloop what function use when you click
    t.onscreenclick(get) 
    
    # start "the engine" (event loop)
    t.mainloop()