You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python全局变量未定义报错:name 'i' is not defined问题求助

解决Tkinter进度条代码中name 'i' is not defined错误

问题原因

你在main()函数内部定义了i = 0(属于函数局部变量),但嵌套的load()函数里用global i声明,会让Python去寻找模块级的全局变量i,而非main()里的局部变量,因此触发未定义报错。

两种修复方案

方案1:使用nonlocal声明(推荐,避免污染全局命名空间)

因为load()是嵌套在main()内的函数,用nonlocal i代替global i,可以让Python直接引用外层main()函数中的局部变量i。

方案2:将i设为模块级全局变量

在main()函数外部定义i = 0,这样load()里的global i就能找到对应的全局变量。

修复后的完整代码

from tkinter import *
from tkinter.ttk import Progressbar
import sys

def main():
    root = Tk()
    root.title("My Application")
    root.resizable(0, 0)
    height = 430
    width = 530
    root.config(bg='#b800c4')

    x = (root.winfo_screenwidth()//2) - (width//2)
    y = (root.winfo_screenheight()//2) - (height//2)
    root.geometry('{}x{}+{}+{}'.format(width, height, x, y))

    exit_btn = Button(root,text='X',command=lambda:exit_window(), font=("Yu gothic ui", 15, 'bold'),fg='yellow',
                bg= '#b800c4', bd=0, activebackground='#b800c4')
    exit_btn.place(x=490, y=0)

    # 修复无框窗口语法错误
    root.overrideredirect(True)

    progress_label = Label(root, text="Please wait...", font=("Yu gothic ui", 15, 'bold'),bg='#b800c4')
    progress_label.place(x=190, y=250)

    progress = Progressbar(root, orient=HORIZONTAL, length=500, mode='determinate')
    progress.place(x=15, y=350)

    i = 0

    def load():
        # 引用外层main函数的局部变量i
        nonlocal i
        if i <= 10:
            txt = 'Please wait ...' +(str(10*i)+'%')
            progress_label.config(text=txt)
            progress_label.after(500, load)
            progress['value'] = 10*i
            i += 1
        else:
            # 进度完成后销毁启动窗口
            root.destroy()
    load()

    # 修复函数缩进问题
    def exit_window():
        root.destroy()
        sys.exit()

    # 启动Tkinter事件循环
    root.mainloop()

if __name__ == '__main__':
    main()

额外修复点说明

  • 补全root.overrideredirect(True)的括号,启用无框窗口效果
  • 修正exit_window函数的缩进错误,调整窗口销毁与程序退出的顺序
  • 添加root.mainloop(),确保Tkinter窗口正常启动事件循环

内容的提问来源于stack exchange,提问作者Cris Uy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:15:36