简体   繁体   中英

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. 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.

Currently I open the window just by assigning turtle.Turtle() to a variable like this:

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

It accomplishes this by "reaching under the covers" and getting the underlying tkinter root window and manipulating it. 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"). 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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