我正在为学校项目编写Python代码。该程序将根据用户输入绘制多个圆圈(2-6个圆圈)。我已经做到了,但是现在需要根据用户输入绘制多行圆圈。例如,如果用户选择3个圆,则我需要按3个圆绘制3个圆。
#import tkinter and turtle
import tkinter as tk
from turtle import *
#ask for user input using tkinter
from tkinter import simpledialog
application_window = tk.Tk()
answer = simpledialog.askinteger('Request', 'number of circles(2-6)?',
parent=application_window, minvalue=2, maxvalue=6)
#set position of turtle and define turtle
t = Turtle()
t.penup()
t.setpos(-200,-200)
t.pendown()
#draw appropriate number of circles using loop
i = 2
for i in range (answer):
circle(30)
penup()
forward(60)
pendown()
i = +1
答案 0 :(得分:0)
别让我们做功课。告诉我们问题,告诉我们您尝试过的内容,然后提出问题。例如,“如何使乌龟画三行圆?”
围绕您已经拥有的for
循环和另一个for
循环。每次外部循环运行时,内部循环将运行以创建一行,然后在下一次迭代之前将乌龟向下移动。
#import tkinter and turtle
import tkinter as tk
from turtle import *
#ask for user input using tkinter
from tkinter import simpledialog
application_window = tk.Tk()
answer = simpledialog.askinteger('Request', 'number of circles(2-6)?',
parent=application_window, minvalue=2, maxvalue=6)
#set position of turtle and define turtle
t = Turtle()
t.penup()
t.setpos(-200,-200)
t.pendown()
#draw appropriate number of circles using loop
for row in range(answer):
for col in range(answer):
circle(30)
penup()
forward(60) # must be undone after loop
pendown()
penup()
backward(60) # undo the backward on line 20
backward(60 * col) # go backwards the length of the diameter times the number of circles
right(90) # turn right 90 degrees
forward(60) # forward the length of one diameter
left(90) # turn back left 90 degrees
pendown()
答案 1 :(得分:0)
我提供@JacksonH解决方案的替代解决方案有两个原因:首先,如果您使用的是Python 3(并且应该应该是),那么您就不需要掌握了simpledialog
在tkinter之外,请改用Python 3 turtle的numinput()
(和textinput()
);其次,美学目标应该是使乌龟尽可能少地移动以达到您的结果,即使这需要更多,更智能的代码。观察此解决方案与其他解决方案的绘制方式之间的区别:
from turtle import Screen, Turtle
# Ask for user input
DEFAULT_COUNT = 3
screen = Screen()
answer = screen.numinput('Request', 'number of circles(2-6)?', default=DEFAULT_COUNT, minval=2, maxval=6)
if answer is None:
answer = DEFAULT_COUNT
else:
answer = int(answer) # int for range()
# define turtle and set position of turtle
turtle = Turtle()
turtle.speed('fast') # because I have little patience
turtle.penup()
turtle.setpos(-200, -200)
direction = 1
# draw appropriate number of circles using nested loops
for row in range(answer - 1, -1, -1): # loop backward to use last iteration as a flag
for column in range(answer - 1, -1, -1):
turtle.pendown()
turtle.circle(30 * direction)
turtle.penup()
if column:
turtle.forward(60) # not done final time
if row: # every time but the last
turtle.left(90 * direction) # turn +/-90 degrees
turtle.forward(60) # forward the length of one diameter
turtle.left(90 * direction) # turn +/-90 degrees
direction *= -1 # reverse our sense of direction
turtle.hideturtle()
screen.exitonclick()