Home > Mobile >  How to use variable declared inside function outside of it?
How to use variable declared inside function outside of it?

Time:02-19

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:

def a:
    b = hello world

q = Label(textvariable=var).pack

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.

CodePudding user response:

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.

CodePudding user response:

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 !

  • Related