当我尝试使用Python在画布上绘制一组漂亮的线条时,我无法使For Loop正确运行。我打算让For Loop与注释掉的代码所做的工作类似。不幸的是,该代码根本不起作用,仅导致了错误消息。
对于For Loop,我想做的是使变量“ linecounter”的值增加20倍20次,然后使行的x坐标每次向右增加50个像素。就目前的当前代码而言,它根本无法工作。
我的For Loop中是否有写得不太正确的东西?
import tkinter as tk
root = tk.Tk()
root.geometry("960x600")
canvas = tk.Canvas(width=960, height=900, bg='white')
canvas.grid(row=2, column=0, columnspan=3)
##canvas.create_line(0, 50, 0, 100, width=5, fill="black")
##canvas.create_line(50, 50, 50, 100, width=5, fill="black")
##canvas.create_line(100, 50, 100, 100, width=5, fill="black")
##canvas.create_line(150, 50, 150, 100, width=5, fill="black")
##canvas.create_line(200, 50, 200, 100, width=5, fill="black")
##canvas.create_line(250, 50, 250, 100, width=5, fill="black")
##canvas.create_line(300, 50, 300, 100, width=5, fill="black")
##canvas.create_line(350, 50, 350, 100, width=5, fill="black")
##canvas.create_line(400, 50, 400, 100, width=5, fill="black")
##canvas.create_line(450, 50, 450, 100, width=5, fill="black")
##canvas.create_line(500, 50, 500, 100, width=5, fill="black")
##canvas.create_line(550, 50, 550, 100, width=5, fill="black")
##canvas.create_line(600, 50, 600, 100, width=5, fill="black")
##canvas.create_line(650, 50, 650, 100, width=5, fill="black")
##canvas.create_line(700, 50, 700, 100, width=5, fill="black")
##canvas.create_line(750, 50, 750, 100, width=5, fill="black")
##canvas.create_line(800, 50, 800, 100, width=5, fill="black")
##canvas.create_line(850, 50, 850, 100, width=5, fill="black")
##canvas.create_line(900, 50, 900, 100, width=5, fill="black")
##canvas.create_line(950, 50, 950, 100, width=5, fill="black")
##canvas.create_line(1000, 50, 1000, 100, width=5, fill="black")
for linecounter 1 to 20
canvas.create_line((linecounter * 50), 50, (linecounter * 50), 100, width=5, fill="black")
root.mainloop()
答案 0 :(得分:2)
for linecounter in range(21):
canvas.create_line((linecounter * 50), 50, (linecounter * 50), 100, width=5, fill="black")
答案 1 :(得分:2)
您可以在以下位置找到解决问题所需的信息: https://wiki.python.org/moin/ForLoop
您应该利用Google来解决诸如此类的简单问题。您将问题缩小到for循环中,而搜索“ For Loops Python”可能已向您显示了执行此操作的正确方法。
您的for循环需要重写为:
for linecounter in range(20):
canvas.create_line((linecounter * 50), 50, (linecounter * 50), 100, width=5, fill="black")
这将从0迭代到19。要从0迭代到20,这似乎是您要尝试的操作,请使用:
for linecounter in range(21):
canvas.create_line((linecounter * 50), 50, (linecounter * 50), 100, width=5, fill="black")