简体   繁体   English

如何控制龟图形窗口的打开和关闭?

[英]How to control opening and closing of the turtle graphics window?

I am writing a program for generating images using the python turtle graphics module. 我正在编写一个使用python turtle图形模块生成图像的程序。 Is there a way to control when the window opens and closes? 有什么方法可以控制何时打开和关闭窗口? I know that turtle.bye() and turtle.exitonclick() close the window, but then it is problem to open it again. 我知道turtle.bye()turtle.exitonclick()关闭了窗口,但是再次打开它是个问题。

Currently I open the window just by assigning turtle.Turtle() to a variable like this: 目前,我只是通过将turtle.Turtle()分配给这样的变量来打开窗口:

t = turtle.Turtle()

I looked in documentation and also here but I didn't find anything. 我看了文档,也看了这里,但是什么也没找到。

Here's something demonstrating how to hide and redisplay the turtle-graphics window without requiring user input to do so. 这说明了如何隐藏和重新显示海龟图形窗口而无需用户输入。 It uses the tkinter after() method to schedule a future call to the function I've named do_turtle_stuff() (if you're interested). 它使用tkinter after()方法来安排将来调用我已命名为do_turtle_stuff()的函数(如果您有兴趣)。

It accomplishes this by "reaching under the covers" and getting the underlying tkinter root window and manipulating it. 它通过“深入了解”并获取基础的tkinter根窗口并对其进行操作来实现此目的。 To allow the user to execute several "commands" it reschedules itself to run gain by making a call to after() itself (unless the user typed in "exit"). 为了允许用户执行几个“命令”,它通过调用after()本身来重新安排自己的运行时间(除非用户键入“ exit”)。 You may not need to that for what you're doing. 您可能不需要在做什么。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM