Home > Blockchain >  How would I go about using a float that I modified in one function into a main function?
How would I go about using a float that I modified in one function into a main function?

Time:07-04

I have a float number called r1x that I modified in a function. I want to use that float number in the main function. I tried declaring it a global var, but it still gives me an error saying it's undefined.

import tkinter
import random
def random_location_no():
    global r1x
    #global r1y
    print('no pressed')
    r1x = round(random.uniform(0.6, 0.8), 2)
    r1x = float(r1x)
    print(r1x)
    return r1x
    
    
def main(): 
    global window
    #global r1x
    window = tkinter.Tk()
    window.title ('iq test')
    window.geometry('800x800')
    
    txt = tkinter.Label(window, text = ' Are you stupid :3', font = ("Oswald", 45, "bold"))
    txt.place(relx=0.5, rely=0.22, anchor="c")
    
    no_button = tkinter.Button (window, text = 'No', fg = 'Black', height = 5, width = 10, command = random_location_no, font = ('Finlandica', 15))
    no_button.place(relx = r1x, rely = 0.55, anchor = 'c')
    
    yes_button = tkinter.Button (window, text = 'Yes', fg = 'Black', height = 5, width = 10, command = yes_press, font = ('Finlandica', 15))
    yes_button.place(relx = 0.3, rely = 0.55, anchor = 'c')
    
    
    
    window.mainloop()

main()

in the code, r1x is a float in the function random_location_no.

I want to use r1x in the main function, in line 24. I tried declaring it as a global var, but it still gives me the error.

Any ideas are appreciated! Thanks

CodePudding user response:

When you declare something as a global variable inside a function, it doesn't get defined until that function actually gets run. no_button.place(relx = r1x, rely = 0.55, anchor = 'c') does run the function, but it also calls for r1x to already be defined, so you'd have to either run your function once first before doing no_button.place(relx = r1x, rely = 0.55, anchor = 'c'), or initialize r1x to some value at the beginning of your main function.

CodePudding user response:

You shouldn't use global variables, maybe just pass first function as an argument to the second function like this:

def generate_number():
    return 10

def get_number(func):
    return func()

get_number(generate_number)

or in your case just do it like this:

def random_location_no():
    ...
    ...
    return r1x

def main(random_number): 
    number = random_number()
    ...
    ...

main(random_location_no)

and for your information, when ever you call the function, variables are created at the call time, so, local (or even global variables that you make them global by passing global keyword) life time finished when the function return, so, if u want to get the value return from a function u need to call it in another function.

  • Related