'How to use variable declared inside function outside of it?

How do I use a variable that I declared inside a function outside one. Do I have to declare a function first and then use it? Using global doesn't work, so what do I do?

I am using the variable inside a tkinter Label function, like so:

from tkinter import *
root = Tk()
def a():
    b = "hello world"

a()
q = Label(root, textvariable=b).pack()
root.mainloop()

So that might be a part of the issue, but I'm still not sure.
The error message simply says the variable doesn't exist.



Solution 1:[1]

Before assigning a variable to a label which was inside a function, you need to call the function at least once to initiate the variable. Furthermore, to call a variable outside of your function you need to use the global function inside it. I know it sounds confusing but the code down below will work:

from tkinter import *

root = Tk()

def a():
  global b # making the variable a global variable to be able to call it out of the function
  b = "hello world"


a() #initiate the variable by calling the function
q = Label(root,text=b) 
q.pack()

root.mainloop()

Tell me if this worked ! ?

Solution 2:[2]

I believe you are misusing global.

In order to change the scope of a variable to the global scope you need to do that in separate statement, as in:

def a:
    global b
    b = hello world

q = Label(textvariable=b).pack

for more examples please check: https://www.w3schools.com/python/python_variables_global.asp

With that said. Using global might not be the best code design choice to use. Scope helps keep things modular and organised.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flusten
Solution 2 Ouss