turtle.Screen().screensize() not outputting the right screensize [duplicate]

℡╲_俬逩灬. 提交于 2020-06-17 07:59:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!