Python全局变量未定义


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

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():
global 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
load()
def exit_window():
sys.exit(root.destroy())

if __name__ == '__main__':
main()
output: name 'i' is not defined
File "C:UsersccreyesDesktop100 days coding challangeLoginPage.py", line 35, in load
if i <= 10:
File "C:UsersccreyesDesktop100 days coding challangeLoginPage.py", line 41, in main
load()
File "C:UsersccreyesDesktop100 days coding challangeLoginPage.py", line 54, in <module>
main()

这是代码的简化版本,有相同的错误:

def main():
i = 0
def load():
global i
if i <= 10:
i += 1
load()
if __name__ == '__main__':
main()

在函数main((之外定义i可以解决问题,如下所示:

i = 0
def main():
def load():
global i
if i <= 10:
i += 1
load()
if __name__ == '__main__':
main()

或者完全去掉main((函数。

最新更新