[SOLVED] How to use variable declared inside function outside of it?

Issue

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"

a()
q = Label(textvariable=b).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.

Solution

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 ! 👍

Answered By – Flusten

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.