Global variable for Python directory storage

Asked

Viewed 400 times

0

Good afternoon Personal,

I am creating a program in python using the Tkinter GUI that use several screens and in the GUI configuration I need to call some text and image files. I would like the help of the gentlemen to find a way to use a variable where I can save the path of the venv directory that are images and text files facilitating the call of these files.

follows an example below of how I am using, but need to create the variable on each screen of the program for the variable to work.

import tkinter as tk
from tkinter import font  as tkfont

dir_venv = 'C:\\Users\cs305672\\PycharmProjects\\SACER\\venv'

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        imagem = tk.PhotoImage(file=dir_venv+'\\img\\logo_xxx.PNG')
        label = tk.Label(self, text="Bem vindo ao sistema de configuração de equipamentos de rede",
                     font=controller.title_font)
        label_logo = tk.Label( self, image=imagem)
        label_logo.imagem = imagem
        label_logo.pack( side='top', padx=10, pady=10 )
        label.pack(side="top", fill="x", pady=5)
        lf1 = tk.LabelFrame(self, text="Escolha a marca do equipamento ou serviço que deseja acessar:",
                        font=("Arial", 15, "bold"), bd=5)
        button1 = tk.Button(lf1, text="Cisco", width=15,height=3,font=("Arial", 15, 'bold'),
                        command=lambda: controller.show_frame("TelaCisco"))
        button2 = tk.Button(lf1, text="Orbit", width=15,height=3, font=("Arial", 15, 'bold'),
                        command=lambda: controller.show_frame("TelaOrbit"))
        button3 = tk.Button( lf1, text="Raisecom",width=15,height=3, font=("Arial", 15, 'bold'),
                         command=lambda: controller.show_frame("TelaRaisecom"))
        button4 = tk.Button( lf1, text="Fibra", width=15, height=3, font=("Arial", 15, 'bold'),
                         command=lambda: controller.show_frame("TelaFibra"))

        button1.pack(side='top', fill='x', padx=10, pady=7)
        button2.pack(side='top', fill='x', padx=10, pady=7)
        button3.pack(side='top', fill='x', padx=10, pady=7)
        button4.pack(side='top', fill='x', padx=10, pady=7)

         lf1.pack(side='left', fill='both', padx=50, pady=50, ipadx=700, ipady=500 )

2 answers

0


Variables in a module, as well as functions and classes, can be imported in Python.

So if your project has a "config.py" file that has a "data_path" variable, anywhere you want to use it, just do it:

from meu_projeto.config import data_path

Now - if your project is not properly configured as a Python package in the current environment, this line will fail, because Python does not understand what is "myproject". For this to work you have to have the folder where this folder is "myproject" inside PYTHONPATH - (if it is the working directory where Python is called, it already works) - but preferably your project has to be installable in virtualenv.

For this, just have a minimum file of setup.py that you can enrich as the project uses more resources.

This file only needs to have a call to setuptools.setup passing the folder where your files are (until the project name he "guesses"):

from setuptools import setup, find_packages

setup(
    name='meu_projeto',
    packages=find_packages(),    
)

(Then see the documentation of how to improve this file - https://packaging.python.org/tutorials/packaging-projects/ )

Having this file in place, you should install your package for development in the virtual environment in which it will run. You’re using pycharm, and pycharm tries to abstract the "virtual environment" and create it all by itself, it shortens a few steps, but people unlearn, or worse, never learn the foundation of these compartmentalized Python environments.

Anyway, with the virtual environment of the project active, in the folder where setup.py is, type python setup.py develop, or pip install -e .

And finally, the way you’re doing it, your program will work - as long as you’re on your computer, and running it from inside the pycharm. : -) Since the path to the virtual environment is hard-coded within the code - a bad idea: anyone running your program would have to edit this variable.

A Python file always knows which folder it is in: the variable __file__ exists in each module running Python and has the full path to the file.

If the virtualenv path is desired, it is also possible to - the variable sys.executable points to the Python of the virtualenv being used.

In turn, the class pathlib.Path facilitates, among other things, getting the directory that contains a file, using the attribute ". Parent" (thus avoiding gymnastics such as __file__.rsplit("/", 1)[0]).

In your, in the file you choose to leave these settings you want to share with the other files:

import sys
from pathlib import Path

dir_venv = Path(sys.executable).parent.parent

And, reiterating, then in the other files just do from meu_projeto.config import dir_venv

-1

Try calling the variable inside each function less where you first declared

global dir_env

Browser other questions tagged

You are not signed in. Login or sign up in order to post.