Home > Software design >  Python Global variable not define
Python Global variable not define

Time:09-29

    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:\Users\ccreyes\Desktop\100 days coding challange\LoginPage.py", line 35, in load
    if i <= 10:
  File "C:\Users\ccreyes\Desktop\100 days coding challange\LoginPage.py", line 41, in main
    load()
  File "C:\Users\ccreyes\Desktop\100 days coding challange\LoginPage.py", line 54, in <module>
    main()

CodePudding user response:

This is a simplified version of the code with the same error:

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

Defining i outside the function main() would solve the problem, like this:

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

Or just get rid of the main() function entirely.

  • Related