我正在尝试使用乌龟图形创建奥地利国旗。这是我的示例代码:
import turtle
def rectangle(t,wdth,ht,c):
t.fillcolor(c)
t.begin_fill()
for i in range(2):
t.forward(ht)
t.left(90)
t.forward(wdth)
t.left(90)
t.end_fill()
def rectangle2(t,wdth,ht,c):
t.fillcolor(c)
t.begin_fill()
for i in range(2):
t.forward(ht)
t.left(90)
t.forward(wdth)
t.left(90)
t.end_fill()
def flag():
flag = turtle.Turtle()
rectangle(flag,50,250,"red")
turtle.up()
def flag2():
flag= turtle.Turtle()
rectangle(flag, 50, 250, "white")
flag()
flag2()
turtle.done()
我的代码创建了一个红色矩形,我打算将其作为标志的底部三分之一。我希望乌龟向上移动,成为奥地利国旗的中间部分,这是一个白色的矩形。
我的代码按预期创建了红色矩形,然后乌龟将红色矩形重新着色为白色。这给我留下了一个白色矩形,而不是一个红色矩形和一个白色矩形。
答案 0 :(得分:0)
编辑:我将width
替换为height
,正如@cdlane在评论中正确指出的那样。
在绘制白色矩形之前,使用forward/left/right
或goto(x, y)
将乌龟移动到正确的位置。
import turtle
def rectangle(height, width, color):
turtle.fillcolor(color)
turtle.begin_fill()
for _ in range(2):
turtle.forward(width)
turtle.left(90)
turtle.forward(height)
turtle.left(90)
turtle.end_fill()
rectangle(50, 250, "red") # bottom red
turtle.left(90) #
turtle.forward(50) # go 50 pixel up
turtle.right(90) #
rectangle(50, 250, "white") # middle white
turtle.left(90) #
turtle.forward(50) # go 50 pixel up
turtle.right(90) #
rectangle(50, 250, "red") # top red
turtle.done()
答案 1 :(得分:0)
三个想法:你让它变得比必要更难;你需要在维基百科中查找奥地利国旗以获得适当的宽高比;这样做的方法不止一种。
首先,让我们简化并清理您的代码:
from turtle import Turtle, Screen
HEIGHT = 120
WIDTH = 3 * HEIGHT / 2
def rectangle(turtle, width, height, color):
turtle.fillcolor(color)
turtle.begin_fill()
for _ in range(2):
turtle.forward(width)
turtle.left(90)
turtle.forward(height)
turtle.left(90)
turtle.end_fill()
def flag(turtle):
turtle.pencolor('black')
rectangle(turtle, WIDTH, HEIGHT, 'white')
rectangle(turtle, WIDTH, HEIGHT / 3, 'red')
turtle.sety(turtle.ycor() + 2 * HEIGHT / 3)
rectangle(turtle, WIDTH, HEIGHT / 3, 'red')
yertle = Turtle(visible=False)
screen = Screen()
flag(yertle)
screen.mainloop()
但是对于这样的颜色块,我更喜欢标记到绘图:
from turtle import Turtle, Screen
HEIGHT = 120
WIDTH = 3 * HEIGHT / 2
STAMP_SIZE = 20
def flag(turtle, width, height):
turtle.penup()
turtle.color('black', 'white')
turtle.shapesize(height / STAMP_SIZE, width / STAMP_SIZE)
turtle.stamp()
turtle.color('black', 'red')
turtle.sety(turtle.ycor() - height / 3)
turtle.shapesize(height / 3 / STAMP_SIZE, width / STAMP_SIZE)
turtle.stamp()
turtle.sety(turtle.ycor() + 2 * height / 3)
turtle.stamp()
yertle = Turtle('square', visible=False)
screen = Screen()
flag(yertle, WIDTH, HEIGHT)
screen.mainloop()
最后,让我们把它简化为非常简单的乌龟逻辑:
from turtle import Turtle, Screen
import tkinter as _
_.ROUND = _.BUTT
HEIGHT = 120
WIDTH = 3 * HEIGHT / 2
def flag(turtle, width, height):
turtle.pensize(height)
turtle.color('red')
turtle.forward(width)
turtle.pensize(height / 3)
turtle.color('white')
turtle.backward(width)
yertle = Turtle(visible=False)
screen = Screen()
screen.bgcolor('black')
flag(yertle, WIDTH, HEIGHT)
screen.mainloop()