如何控制海龟图形的开合window?
How to control opening and closing of the turtle graphics window?
我正在编写一个使用 python 海龟图形模块生成图像的程序。有没有办法控制 window 何时打开和关闭?我知道 turtle.bye()
和 turtle.exitonclick()
关闭了 window,但是再次打开它是个问题。
目前我打开 window 只是通过将 turtle.Turtle()
分配给这样的变量:
t = turtle.Turtle()
我查看了文档和此处,但没有找到任何内容。
这里展示了如何隐藏和重新显示海龟图形 window 而无需用户输入。它使用 tkinter after()
方法来安排将来调用我命名为 do_turtle_stuff()
的函数(如果您有兴趣的话)。
它通过 "reaching under the covers" 并获取底层 tkinter
根 window 并对其进行操作来完成此操作。为了允许用户执行多个 "commands",它通过调用 after()
本身(除非用户输入 "exit")重新安排自己获得 运行。对于您正在做的事情,您可能不需要这样做。
import turtle
def do_turtle_stuff(root):
user_input = input('Enter command ("foo", "bar", or "exit"): ')
if user_input == "exit":
root.withdraw() # Hide the turtle screen.
root.quit() # Quit the mainloop.
return
elif user_input == "foo":
turtle.forward(50)
turtle.left(90)
turtle.forward(100)
elif user_input == "bar":
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
else:
print('Unknown command:', user_input)
root.after(0, lambda: do_turtle_stuff(root))
root = turtle.getscreen()._root
root.after(0, lambda: do_turtle_stuff(root))
root.mainloop()
print('back in main')
input('Press Enter key to do more turtle stuff ')
root.state('normal') # Restore the turtle screen.
root.after(0, lambda: do_turtle_stuff(root))
root.mainloop()
print('done')
我正在编写一个使用 python 海龟图形模块生成图像的程序。有没有办法控制 window 何时打开和关闭?我知道 turtle.bye()
和 turtle.exitonclick()
关闭了 window,但是再次打开它是个问题。
目前我打开 window 只是通过将 turtle.Turtle()
分配给这样的变量:
t = turtle.Turtle()
我查看了文档和此处,但没有找到任何内容。
这里展示了如何隐藏和重新显示海龟图形 window 而无需用户输入。它使用 tkinter after()
方法来安排将来调用我命名为 do_turtle_stuff()
的函数(如果您有兴趣的话)。
它通过 "reaching under the covers" 并获取底层 tkinter
根 window 并对其进行操作来完成此操作。为了允许用户执行多个 "commands",它通过调用 after()
本身(除非用户输入 "exit")重新安排自己获得 运行。对于您正在做的事情,您可能不需要这样做。
import turtle
def do_turtle_stuff(root):
user_input = input('Enter command ("foo", "bar", or "exit"): ')
if user_input == "exit":
root.withdraw() # Hide the turtle screen.
root.quit() # Quit the mainloop.
return
elif user_input == "foo":
turtle.forward(50)
turtle.left(90)
turtle.forward(100)
elif user_input == "bar":
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
else:
print('Unknown command:', user_input)
root.after(0, lambda: do_turtle_stuff(root))
root = turtle.getscreen()._root
root.after(0, lambda: do_turtle_stuff(root))
root.mainloop()
print('back in main')
input('Press Enter key to do more turtle stuff ')
root.state('normal') # Restore the turtle screen.
root.after(0, lambda: do_turtle_stuff(root))
root.mainloop()
print('done')