How to access a variable in a function?

for example, there is a code:

def func1(): a = Label(text='aaa') a.destroy() 

But this will generate an error, so how do you refer to this variable?

  • No Either declare a variable in the desired scope, or return it from a function. - Sergey Gornostaev 2:51 pm

3 answers 3

First, if you want to use the Tkinter library, you need to import it and create a window. This is done like this:

 from tkinter import * root = Tk() 

Then we create this variable in the function, before declaring it global:

 def func1(): global a a = Label(text = 'aaa') 

And then, we can perform an action with it outside the function, for example, place it using the pack () method.

 a.pack() 

At the end, be sure to write:

 root.mainloop() 
  • 6
    Global variables are evil. The need to use the global operator is a signal that something is wrong with your code. - Sergey Gornostaev
  • 3
    In the question itself laid the wrong course of thought. Topicaster is trying to do something wrong. To suggest how to do this is hardly the best solution. For example, change the function to return a value. - 0xdb

How to access a variable in a function?

One of the important properties of the function is to hide its implementation, i.e. No need to know how it works inside. If there is a need to deprive her of this, then the function in this place is not needed:

 a = Label(text='aaa') a.destroy() 

To use a function, you only need to know its name, its arguments, and what it returns as a result:

 def createLabel (text): a = Label (text=text) return a a = createLabel ('my label') 
     def func1(): func1.a = Label(text='aaa') func1.a.destroy() 

    But this is a very bad practice.


    Pulp fiction on topic .

    • One piece of advice is trenchant ... Passing data through an attribute of a function is not only a global, so also implicit state. - Sergey Gornostaev
    • one
      @SergeyGornostaev But after all, a person needs exactly this, as I understood. The fact that his architecture is bad is another question. - Mikhail Murugov