它告诉我“期望缩进块”有人可以帮助我吗?

时间:2018-12-08 17:51:44

标签: python

def run():
        global var
        var = something()
for x in range(10):
        if x < 0:
        return
    from tkinter import *
    master = Tk()

    canvas_width = 2000
    canvas_height = 1000

    w = Canvas(master, 
                width=canvas_width,
                height=canvas_height)
    w.pack()

    y = int(canvas_height / 2)
    # w.create_line(0, y, canvas_width, y, fill="#476042")
    # w.Label(0, y, canvas_width, y, text="Hello Tkinter!")
    w.create_text(y, y, text="Take your shot", font="Helvetica 115 bold")
    mainloop()

    run()

2 个答案:

答案 0 :(得分:3)

尝试以这种方式设置代码格式!缩进在Python中很重要。 Python希望缩进属于控制语句(或任何以冒号结尾的语句)的指令。

from tkinter import *

def run():
    global var
    var = something()
for x in range(10):
    if x < 0:
        return    
    master = Tk()

    canvas_width = 2000
    canvas_height = 1000

    w = Canvas(master, 
               width=canvas_width,
               height=canvas_height)
    w.pack()
    y = int(canvas_height / 2)
    # w.create_line(0, y, canvas_width, y, fill="#476042")
    # w.Label(0, y, canvas_width, y, text="Hello Tkinter!")
    w.create_text(y, y, text="Take your shot", font="Helvetica 115 bold")
    mainloop()
    run()

答案 1 :(得分:0)

您的代码格式不正确。 Python希望在if语句后插入一个缩进的块,当找不到该块时,它会抛出IndentationError。只需缩进第6行,便可以使用:

def run():
    global var
    var = something()
for x in range(10):
    if x < 0:
        return
from tkinter import *
master = Tk()

canvas_width = 2000
canvas_height = 1000

w = Canvas(master, 
            width=canvas_width,
            height=canvas_height)
w.pack()

y = int(canvas_height / 2)
# w.create_line(0, y, canvas_width, y, fill="#476042")
# w.Label(0, y, canvas_width, y, text="Hello Tkinter!")
w.create_text(y, y, text="Take your shot", font="Helvetica 115 bold")
mainloop()

run()

Here是有关缩进的简短文章。