问题
I have written some code to place dots all around the screen randomly; however, it does not cover the entire screen:
import turtle
import random
t = turtle.Turtle()
color = ["red", "green", "blue", "pink", "yellow", "purple"]
t.speed(-1)
for i in range(0, 500):
print(turtle.Screen().screensize())
z = turtle.Screen().screensize()
x = z[0]
y = z[1]
t.color(color[random.randint(0,5)])
t.dot(4)
t.setposition(random.randint(-x,x), random.randint(-y,y))
turtle.done()
output
回答1:
"Screen" refers to the turtle's logical boundaries (scrollable area) which may not be the same as the window size.
Call turtle.setup(width, height) to set your window size, then use the turtle.window_width() and turtle.window_height()
functions to access its size.
You could also make sure the screensize
matches the window size, then use it as you are doing. Set the screen size with turtle.screensize(width, height).
Additionally, your random number selection is out of bounds. Use
random.randint(0, width) - width // 2
to shift the range to be centered on 0.
Putting it together:
import turtle
import random
turtle.setup(480, 320)
color = ["red", "green", "blue", "pink", "yellow", "purple"]
t = turtle.Turtle()
t.speed("fastest")
for _ in range(0, 100):
t.color(random.choice(color))
t.dot(4)
w = turtle.window_width()
h = turtle.window_height()
t.setposition(random.randint(0, w) - w // 2, random.randint(0, h) - h // 2)
turtle.exitonclick()
来源:https://stackoverflow.com/questions/60357667/turtle-screen-screensize-not-outputting-the-right-screensize