pythonfunctionvariablesgloballocal

local variables outside a function in python


i have a code that goes like this

def inputs():
    q_number = int(1)
    number_of_q = int(0)
    q = {}
    x = {}
    y = {}
    xxxx = 1
    for i in range(4):
        C = float(qq[xxxx].get())
        X = float(xxx[xxxx].get())
        Y = float(yy[xxxx].get())
        if C != 0 or C != "":
            q[q_number] = C
            x[q_number] = X
            y[q_number] = Y
            q_number += 1
            number_of_q += 1

it works fine the only problem i have is i am trying to print the duples q , x , y outside of the function so i can use them in other stuff but it just wont work

i have tried to write the functiona as normal and global the duple q x y outside of the function

def inputs():
    q_number = int(1)
    number_of_q = int(0)
    q = {}
    x = {}
    y = {}
    xxxx = 1
    for i in range(4):
        C = float(qq[xxxx].get())
        X = float(xxx[xxxx].get())
        Y = float(yy[xxxx].get())
        if C != 0 or C != "":
            q[q_number] = C
            x[q_number] = X
            y[q_number] = Y
            q_number += 1
            number_of_q += 1
    global number_of_q, q_number, q, x, y
    print(number_of_q, q_number, q, x, y)

but the program gives me an error ( NameError: name 'number_of_q' is not defined ) can someone help me out ?


Solution

  • The below creates groups of StringVar. The update_fltdb function mirrors the StringVar groups to fltdb as float values. I fleshed it out with the 12 Entry widgets, and the Button.

    import tkinter as tk
    
    root  = tk.Tk()
    
    SVDB  = ([], [], []) #groups of StringVar
    fltdb = ([], [], []) #groups of float
    
    
    #mirror SVDB as float results
    def update_fltdb() -> None:
        fltdb = ([], [], [])
        for group, out in zip(SVDB, fltdb):
            for sv in group:
                try   : out.append(float(sv.get()))
                except: 
                    sv.set('0.0')
                    out.append(0.0)
        
        print(fltdb)
        
    
    #build stringvar database
    for x, group in enumerate(SVDB):
        for y in range(4):
            (sv := tk.StringVar(root)).set(f'{x}.{y}')
            tk.Entry(root, textvariable=sv).grid(column=x, row=y, sticky='nswe')
            group.append(sv)
    
    
    #button
    button = tk.Button(root, text='click', command=update_fltdb)
    button.grid(column=x, row=y+1, sticky='e')
    button.invoke() #update_fltdb
    
    
    if __name__ == '__main__':
        root.mainloop()
    

    You can unpack to any name(s) you need.

    q, x, y    = fltdb
    qv, xv, yv = SVDB