我这里有一个设置代码,我每次运行代码时都会用它来生成一个唯一的图像;如何将其设置为仅在我的tkinter屏幕的边界内绘制?
以下是代码:
import random
import turtle
maker=turtle.Turtle()
maker.getscreen().delay(0)
maker.getscreen().tracer(0)
n=random.randint(1,360)
m=random.randint(0,100)
r=random.randint(0,50)
d=random.randint(1,2)
maker2=maker.clone()
maker3=maker.clone()
maker4=maker.clone()
maker.goto(0,0)
maker2.goto(0,0)
maker3.goto(0,0)
maker4.goto(0,0)
#top right
maker.goto(50, 50)
#bottom right
maker2.goto(50, -50)
#bottom left
maker3.goto(-50, -50)
#top left
maker4.goto(-50, 50)
while r<50:
for i in range (0,m):
maker.forward(m)
maker2.forward(m)
maker3.backward(m)
maker4.backward(m)
for i in range (0,r):
if d == 1:
maker.right(n)
maker2.right(n*-1)
maker3.left(n*-1)
maker4.left(n)
elif d == 2:
maker.left(n)
maker2.left(n*-1)
maker3.right(n*-1)
maker4.right(n)
maker.forward(m)
maker2.forward(m)
maker3.backward(m)
maker4.backward(m)
n=n+1
r = r + 1
n=random.randint(0,359)
maker.goto(0,0)
maker2.goto(0,0)
maker3.goto(0,0)
maker4.goto(0,0)
turtle.exitonclick()
答案 0 :(得分:0)
由于你没有在完成之前显示图形,一个简单的解决方法是进行移动,检查移动是否将你带出画布,然后如果它移动,只需撤消该移动:
from random import randint, choice
from turtle import Turtle, Screen
screen = Screen()
screen.tracer(0)
width, height = screen.window_width() - 30, screen.window_height() - 30 # -30 to account for window borders, etc.
maker1 = Turtle(visible=False)
maker2 = maker1.clone()
maker3 = maker1.clone()
maker4 = maker1.clone()
maker1.goto(50, 50) # top right
maker2.goto(50, -50) # bottom right
maker3.goto(-50, -50) # bottom left
maker4.goto(-50, 50) # top left
n = randint(1, 360)
m = randint(0, 100)
r = randint(0, 50)
d = choice([True, False])
def out_of_bounds(turtle):
return not (-width//2 < turtle.xcor() < width//2 and -height//2 < turtle.ycor() < height//2)
while r < 50:
for i in range(0, m):
maker1.forward(m)
maker2.forward(m)
maker3.backward(m)
maker4.backward(m)
if any(out_of_bounds(turtle) for turtle in screen.turtles()):
for turtle in screen.turtles():
turtle.undo()
if d:
maker1.right(r * n)
maker2.right(-r * n)
maker3.left(-r * n)
maker4.left(r * n)
else:
maker1.left(r * n)
maker2.left(-r * n)
maker3.right(-r * n)
maker4.right(r * n)
maker1.forward(m)
maker2.forward(m)
maker3.backward(m)
maker4.backward(m)
if any(out_of_bounds(turtle) for turtle in screen.turtles()):
for turtle in screen.turtles():
turtle.undo()
r += 1
n = randint(0, 359)
screen.update()
screen.exitonclick()
我同意@ PM2Ring关于调整图像密度(上面是不是一个例子,但你很快就会看到一个)。