简体   繁体   中英

Beginner trying Python Turtle module

I'm a beginner just trying to mess around with Python. I wrote some very simple code using the Turtle module, but something I can't figure out is why the GUI closes immediately after it's done drawing?

I've tried turtle.getscreen()._root.mainloop(), and the sleep command (which my cmd doesn't recognize), but to no avail. Any thoughts?

Realize this is a trivial question, but people say the best way to understand things is to get in there and do random things :)

Code ( extracted from comment):

from turtle import *
setup()
title("turtle test")
clear()
down()
forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)
forward(500)
turtle.getscreen()._root.mainloop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'turtle' is not defined

Because you did from turtle import * you do not have a turtle module for turtle.getscreen()._root.mainloop() , generating the error above.

Instead, try mainloop() .

The screen should not "disappear"- if you are calling the mainloop() method correctly - however, if there is a syntax error in your source code, or other Python exception is raised, the program would finish immediately.

If instead of clicking on your program, you run it from a command terminal, you will see the error traceback.

POst it on your question (along with your code, properly formated, which you can do by clicking on "edit" on the question), so that people may help you further.

(btw, calling the mainloop method in the way you describe is works for me).

Now one thing: the built-in Python Tkinter turtle is mostly a toy, and the fun part is playing along with it in the interactive mode, typing commands to it as you go, not to write a script with it. If you want to do some serious art using a turtle model for driving, you be better writing your own turtle.

像这样修复它

from turtle import *

setup()

title("turtle test")

clear()

down()

forward(50)

right(90)

forward(50)

right(90)

forward(50)

right(90)

forward(500)

done()

My answer would be to remove root because it's not assigned ,here is my code try it out:

from turtle import *
setup()
title("turtle test")
clear()
down()
forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)
forward(500)
mainloop()

Okay this is maybe too much but you can use a for loop(a loop that repeats for some amount of time):

from turtle import *
setup()
title("turtle test")
clear()
down()
for i in range(3):
    forward(50)
    right(90)
forward(500)
mainloop()

Python is a great language consider working on learning it!

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