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?
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?
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() global operator is a signal that something is wrong with your code. - Sergey GornostaevHow 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.
Source: https://ru.stackoverflow.com/questions/980618/
All Articles