【问题标题】:Turtle graphics - How do I control when the window closes?Turtle graphics - 如何控制窗口何时关闭?
【发布时间】:2011-09-08 06:04:38
【问题描述】:

我有一个绘制一些海龟图形的小 Python 脚本。当我的脚本运行完成后,乌龟屏幕会自动关闭,所以为了能看到一段时间的图形,我必须在脚本末尾使用time.sleep(5)来延迟关闭。

有什么方法可以让这更加动态,即告诉 python 我想自己控制窗口的关闭?我不介意脚本在等待我的命令时是否不能做任何其他事情,但如果我不必去控制台获取read() 或其他东西,我会更喜欢。理想情况下,即使脚本完成运行,画布也应该保持打开状态,但我可以接受一个停止脚本的解决方案,直到我关闭包含画布的窗口(或单击画布,或其他任何东西......)。

我该如何做到这一点?

【问题讨论】:

  • python -i script.py 从终端工作
  • 这个问题和答案也适用于用 PyCharm 编写的海龟程序!

标签: python turtle-graphics window-management


【解决方案1】:
import turtle

turtle.forward(100)
turtle.left(90)
turtle.forward(100)
# etc.

turtle.getscreen()._root.mainloop()  # <-- run the Tkinter main loop

(编辑:turtle.done() 下面的 hua 建议不那么难看。)

【讨论】:

  • 完美!脚本停止,直到我关闭窗口,然后继续。
  • 你需要 getscreen()._root 部分吗? turtle.mainloop() 效果很好(在 Python 3 中)...
【解决方案2】:

尝试在代码末尾添加input()

【讨论】:

    【解决方案3】:

    只需使用从turtle模块本身导入的mainloop()函数!

    import turtle
    
    
    #Draw a square
    for i in range(4):
        turtle.forward(200)
        turtle.left(90)
    
    
    #calling for the mainloop()
    turtle.mainloop()
    

    【讨论】:

    • AttributeError: 'Turtle' object has no attribute 'mainloop' PAG's answer 似乎工作正常。
    • @DonKirkby 它的 turtle.mainloop() 而不是 Turtle.mainloop()
    • 你是对的,@DevX,不知道我是怎么弄错的。这个答案现在对我有用。
    【解决方案4】:

    只需使用 turtle.done()turtle.Screen().exitonclick() 作为你的海龟程序的最后一个命令。

    【讨论】:

    • import turtle; turtle.exitonclick() 在 Python 3 中应该足够了。
    【解决方案5】:

    这会等待几次点击 - 并在您点击时绘制一个螺旋线 - 直到它决定在最后一次点击时退出:

    import turtle
    
    
    win = turtle.Screen()
    win.bgcolor("white")
    
    tess = turtle.Turtle()
    
    tess.speed(0)
    tess.color("blue")             
    tess.pensize(5)                 
    offSet=30
    
    def doNextEvent(x,y):
    
        global offSet
        global win
        tess.forward(20)
        tess.left(1+offSet)
        offSet=offSet-2
        if(offSet<1):
            win.exitonclick()
    
    
    win.onclick(doNextEvent)
    win.listen()
    win.mainloop()
    

    【讨论】:

    • 不,它没有:AttributeError: '_Screen' object has no attribute 'mainloop'
    猜你喜欢
    • 2018-06-14
    • 2019-06-09
    • 2021-12-24
    • 1970-01-01
    • 2014-04-11
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多