问题描述
我已经写了一些代码来在屏幕周围随机放置点;但是,它并没有覆盖整个屏幕:
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()
推荐答案
屏幕"是指海龟的逻辑边界(可滚动区域),可能与窗口大小不同.
"Screen" refers to the turtle's logical boundaries (scrollable area) which may not be the same as the window size.
调用turtle.setup(width, height)
设置窗口大小,然后使用 turtle.window_width()
和 turtle.window_height()
函数来访问它的大小.
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.
您还可以确保 screensize
与窗口大小匹配,然后照常使用它.使用 turtle.screensize(宽度、高度)
.
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
将范围移动到以 0 为中心.
to shift the range to be centered on 0.
组合起来:
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()
这篇关于turtle.Screen().screensize() 没有输出正确的屏幕尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!