ctk-idiomas 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctk-idiomas
3
+ Version: 0.1.0
4
+ Summary: Sistema Plug & Play de idiomas e tradução visual para CustomTkinter
5
+ Author: Lucas Gabriel da Costa
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: customtkinter>=5.0.0
9
+
10
+ # 🌐 ctk-idiomas
11
+
12
+ Sistema **Plug & Play** de internacionalização (i18n), troca de idiomas em tempo real e editor visual de traduções para aplicativos feitos com **CustomTkinter**.
13
+
14
+ Com apenas **uma linha de código**, o `ctk-idiomas` injeta um menu suspenso moderno no topo da sua janela, captura automaticamente os textos da interface, gera o arquivo `.ini` e permite que você ou qualquer usuário crie novas traduções sem mexer no código-fonte.
15
+
16
+ ---
17
+
18
+ ## ✨ Funcionalidades
19
+
20
+ - **Zero Configuração de Layout:** Injeta automaticamente um botão de engrenagem (`⚙️`) no canto superior direito da janela com menu suspenso arredondado.
21
+ - **Varredura Automática de Widgets:** Detecta e traduz sozinho:
22
+ - Título da janela (`app.title`)
23
+ - Textos de `CTkLabel`, `CTkButton`, `CTkCheckBox`, `CTkRadioButton` e `CTkSwitch`
24
+ - Campos de entrada `CTkEntry` (`placeholder_text`)
25
+ - Títulos das abas de `CTkTabview`
26
+ - **Mensagens Dinâmicas (`lang.t`):** Registra e traduz textos exibidos apenas em tempo de execução (como `messagebox` ou textos pós-clique), com suporte a variáveis (`{nome}`).
27
+ - **Editor Visual Integrado (`Translate`):** Janela embutida com tabela lado a lado, navegação por teclado (`↑` / `↓`), pré-preenchimento inteligente (mantém o texto original nas frases não traduzidas) e exportação para a área de transferência.
28
+ - **Hot Reload em Tempo Real:** Monitora o arquivo `app.ini` em segundo plano — editou e salvou no bloco de notas, a interface atualiza na hora sem reiniciar o app.
29
+
30
+ ---
31
+
32
+ ## 🛠️ Ferramentas e Tecnologias Utilizadas
33
+
34
+ - **[Python 3.8+](https://python.org):** Linguagem base do projeto.
35
+ - **[CustomTkinter](https://github.com):** Construção dos componentes visuais modernos, janelas auxiliares e menu suspenso estilizado.
36
+ - **`configparser` (Biblioteca Padrão):** Leitura, escrita e gerenciamento estruturado dos arquivos `.ini` em UTF-8.
37
+ - **`tkinter` / `ttk` (Biblioteca Padrão):** Renderização da tabela de tradução (`Treeview`) e controle de eventos de foco/teclado.
38
+ - **`setuptools`:** Empacotamento padrão PEP 621 via `pyproject.toml` para instalação universal via `pip`.
39
+
40
+ ---
41
+
42
+ ## 📦 Instalação
43
+
44
+ ### Instalação local (Modo Desenvolvimento)
45
+ Clone ou baixe este repositório, abra o terminal na pasta raiz (`ctk_idiomas/`) e execute:
46
+
47
+ ```bash
48
+ pip install -e .
49
+ ```
50
+
51
+ ### Instalação via GitHub
52
+ Em qualquer projeto ou computador, instale diretamente pelo terminal:
53
+
54
+ ```bash
55
+ pip install https://github.com/LucasGabrieldaCosta123/ctk-idiomas/archive/refs/heads/main.zip
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 🚀 Como Usar
61
+
62
+ Basta importar `Idiomas` e iniciá-lo logo após criar a janela principal, informando o **`idioma_principal`** em que o aplicativo foi escrito:
63
+
64
+ ```python
65
+ from tkinter import messagebox
66
+ import customtkinter as ctk
67
+ from ctk_idiomas import Idiomas
68
+
69
+ app = ctk.CTk()
70
+ app.title("Meu Aplicativo")
71
+ app.geometry("460x320")
72
+
73
+ # 1. Inicializa o sistema de idiomas (injeta o botão ⚙️ automaticamente)
74
+ lang = Idiomas(app, idioma_principal="Português (Brasil)")
75
+
76
+ # 2. Crie sua interface normalmente
77
+ abas = ctk.CTkTabview(app)
78
+ abas.pack(fill="both", expand=True, padx=15, pady=10)
79
+
80
+ aba_inicio = abas.add("Início")
81
+ aba_sobre = abas.add("Sobre")
82
+
83
+ entrada = ctk.CTkEntry(aba_inicio, placeholder_text="Digite seu nome")
84
+ entrada.pack(pady=(20, 10), fill="x", padx=20)
85
+
86
+ def ao_clicar():
87
+ nome = entrada.get() or "Visitante"
88
+ # 3. Use lang.t() para mensagens dinâmicas em tempo de execução
89
+ messagebox.showinfo(
90
+ lang.t("Aviso"),
91
+ lang.t("Olá, {nome}! Bem-vindo ao sistema.", nome=nome)
92
+ )
93
+
94
+ ctk.CTkButton(aba_inicio, text="Confirmar", command=ao_clicar).pack(pady=10)
95
+ ctk.CTkLabel(aba_sobre, text="Versão 1.0").pack(pady=30)
96
+
97
+ app.mainloop()
98
+ ```
99
+
100
+ ---
101
+
102
+ ## ⚙️ Como Funciona por Dentro
103
+
104
+ 1. **Captura Pós-Montagem (`after`):** Assim que o aplicativo inicia, o `Idiomas` aguarda a montagem dos widgets na tela e percorre recursivamente toda a árvore de componentes (`winfo_children`), mapeando cada widget para um ID numérico (`01`, `02`, `03`...).
105
+ 2. **Geração do `app.ini`:** Na primeira execução, cria o arquivo `app.ini` em UTF-8 na pasta do projeto contendo a seção `[Config]` e a seção do idioma principal definida pelo desenvolvedor.
106
+ 3. **Fallback Seguro:** Caso um usuário crie uma tradução parcial (traduzindo apenas algumas frases), o sistema preenche automaticamente as linhas restantes com o texto do idioma base, evitando campos vazios ou erros na interface.
107
+ 4. **Monitoramento de Arquivo:** A cada `1000ms`, verifica o *timestamp* (`os.path.getmtime`) do `app.ini`. Se houver alteração externa no disco, relê o arquivo e reaplica os textos na janela instantaneamente.
108
+
109
+ ---
110
+
111
+ ## 📄 Exemplo do `app.ini` Gerado
112
+
113
+ ```ini
114
+ [Config]
115
+ idioma = Português (Brasil)
116
+
117
+ [Português (Brasil)]
118
+ _lang_label = Linguagem:
119
+ _translate_btn = Traduzir
120
+ 00_titulo = Meu Aplicativo
121
+ 01 = Início
122
+ 02 = Sobre
123
+ 03 = Digite seu nome
124
+ 04 = Confirmar
125
+ 05 = Versão 1.0
126
+ msg_01 = Aviso
127
+ msg_02 = Olá, {nome}! Bem-vindo ao sistema.
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 📁 Estrutura do Pacote
133
+
134
+ ```text
135
+ ctk_idiomas/
136
+ ├── pyproject.toml # Metadados e dependências do pacote
137
+ ├── README.md # Documentação do projeto
138
+ └── ctk_idiomas/
139
+ ├── __init__.py # Exportação pública da classe Idiomas
140
+ └── nucleo.py # Gerenciador INI, menu suspenso e janela Translate
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 📝 Licença
146
+
147
+ Este projeto é de uso livre para projetos pessoais e comerciais.
@@ -0,0 +1,138 @@
1
+ # 🌐 ctk-idiomas
2
+
3
+ Sistema **Plug & Play** de internacionalização (i18n), troca de idiomas em tempo real e editor visual de traduções para aplicativos feitos com **CustomTkinter**.
4
+
5
+ Com apenas **uma linha de código**, o `ctk-idiomas` injeta um menu suspenso moderno no topo da sua janela, captura automaticamente os textos da interface, gera o arquivo `.ini` e permite que você ou qualquer usuário crie novas traduções sem mexer no código-fonte.
6
+
7
+ ---
8
+
9
+ ## ✨ Funcionalidades
10
+
11
+ - **Zero Configuração de Layout:** Injeta automaticamente um botão de engrenagem (`⚙️`) no canto superior direito da janela com menu suspenso arredondado.
12
+ - **Varredura Automática de Widgets:** Detecta e traduz sozinho:
13
+ - Título da janela (`app.title`)
14
+ - Textos de `CTkLabel`, `CTkButton`, `CTkCheckBox`, `CTkRadioButton` e `CTkSwitch`
15
+ - Campos de entrada `CTkEntry` (`placeholder_text`)
16
+ - Títulos das abas de `CTkTabview`
17
+ - **Mensagens Dinâmicas (`lang.t`):** Registra e traduz textos exibidos apenas em tempo de execução (como `messagebox` ou textos pós-clique), com suporte a variáveis (`{nome}`).
18
+ - **Editor Visual Integrado (`Translate`):** Janela embutida com tabela lado a lado, navegação por teclado (`↑` / `↓`), pré-preenchimento inteligente (mantém o texto original nas frases não traduzidas) e exportação para a área de transferência.
19
+ - **Hot Reload em Tempo Real:** Monitora o arquivo `app.ini` em segundo plano — editou e salvou no bloco de notas, a interface atualiza na hora sem reiniciar o app.
20
+
21
+ ---
22
+
23
+ ## 🛠️ Ferramentas e Tecnologias Utilizadas
24
+
25
+ - **[Python 3.8+](https://python.org):** Linguagem base do projeto.
26
+ - **[CustomTkinter](https://github.com):** Construção dos componentes visuais modernos, janelas auxiliares e menu suspenso estilizado.
27
+ - **`configparser` (Biblioteca Padrão):** Leitura, escrita e gerenciamento estruturado dos arquivos `.ini` em UTF-8.
28
+ - **`tkinter` / `ttk` (Biblioteca Padrão):** Renderização da tabela de tradução (`Treeview`) e controle de eventos de foco/teclado.
29
+ - **`setuptools`:** Empacotamento padrão PEP 621 via `pyproject.toml` para instalação universal via `pip`.
30
+
31
+ ---
32
+
33
+ ## 📦 Instalação
34
+
35
+ ### Instalação local (Modo Desenvolvimento)
36
+ Clone ou baixe este repositório, abra o terminal na pasta raiz (`ctk_idiomas/`) e execute:
37
+
38
+ ```bash
39
+ pip install -e .
40
+ ```
41
+
42
+ ### Instalação via GitHub
43
+ Em qualquer projeto ou computador, instale diretamente pelo terminal:
44
+
45
+ ```bash
46
+ pip install https://github.com/LucasGabrieldaCosta123/ctk-idiomas/archive/refs/heads/main.zip
47
+ ```
48
+
49
+ ---
50
+
51
+ ## 🚀 Como Usar
52
+
53
+ Basta importar `Idiomas` e iniciá-lo logo após criar a janela principal, informando o **`idioma_principal`** em que o aplicativo foi escrito:
54
+
55
+ ```python
56
+ from tkinter import messagebox
57
+ import customtkinter as ctk
58
+ from ctk_idiomas import Idiomas
59
+
60
+ app = ctk.CTk()
61
+ app.title("Meu Aplicativo")
62
+ app.geometry("460x320")
63
+
64
+ # 1. Inicializa o sistema de idiomas (injeta o botão ⚙️ automaticamente)
65
+ lang = Idiomas(app, idioma_principal="Português (Brasil)")
66
+
67
+ # 2. Crie sua interface normalmente
68
+ abas = ctk.CTkTabview(app)
69
+ abas.pack(fill="both", expand=True, padx=15, pady=10)
70
+
71
+ aba_inicio = abas.add("Início")
72
+ aba_sobre = abas.add("Sobre")
73
+
74
+ entrada = ctk.CTkEntry(aba_inicio, placeholder_text="Digite seu nome")
75
+ entrada.pack(pady=(20, 10), fill="x", padx=20)
76
+
77
+ def ao_clicar():
78
+ nome = entrada.get() or "Visitante"
79
+ # 3. Use lang.t() para mensagens dinâmicas em tempo de execução
80
+ messagebox.showinfo(
81
+ lang.t("Aviso"),
82
+ lang.t("Olá, {nome}! Bem-vindo ao sistema.", nome=nome)
83
+ )
84
+
85
+ ctk.CTkButton(aba_inicio, text="Confirmar", command=ao_clicar).pack(pady=10)
86
+ ctk.CTkLabel(aba_sobre, text="Versão 1.0").pack(pady=30)
87
+
88
+ app.mainloop()
89
+ ```
90
+
91
+ ---
92
+
93
+ ## ⚙️ Como Funciona por Dentro
94
+
95
+ 1. **Captura Pós-Montagem (`after`):** Assim que o aplicativo inicia, o `Idiomas` aguarda a montagem dos widgets na tela e percorre recursivamente toda a árvore de componentes (`winfo_children`), mapeando cada widget para um ID numérico (`01`, `02`, `03`...).
96
+ 2. **Geração do `app.ini`:** Na primeira execução, cria o arquivo `app.ini` em UTF-8 na pasta do projeto contendo a seção `[Config]` e a seção do idioma principal definida pelo desenvolvedor.
97
+ 3. **Fallback Seguro:** Caso um usuário crie uma tradução parcial (traduzindo apenas algumas frases), o sistema preenche automaticamente as linhas restantes com o texto do idioma base, evitando campos vazios ou erros na interface.
98
+ 4. **Monitoramento de Arquivo:** A cada `1000ms`, verifica o *timestamp* (`os.path.getmtime`) do `app.ini`. Se houver alteração externa no disco, relê o arquivo e reaplica os textos na janela instantaneamente.
99
+
100
+ ---
101
+
102
+ ## 📄 Exemplo do `app.ini` Gerado
103
+
104
+ ```ini
105
+ [Config]
106
+ idioma = Português (Brasil)
107
+
108
+ [Português (Brasil)]
109
+ _lang_label = Linguagem:
110
+ _translate_btn = Traduzir
111
+ 00_titulo = Meu Aplicativo
112
+ 01 = Início
113
+ 02 = Sobre
114
+ 03 = Digite seu nome
115
+ 04 = Confirmar
116
+ 05 = Versão 1.0
117
+ msg_01 = Aviso
118
+ msg_02 = Olá, {nome}! Bem-vindo ao sistema.
119
+ ```
120
+
121
+ ---
122
+
123
+ ## 📁 Estrutura do Pacote
124
+
125
+ ```text
126
+ ctk_idiomas/
127
+ ├── pyproject.toml # Metadados e dependências do pacote
128
+ ├── README.md # Documentação do projeto
129
+ └── ctk_idiomas/
130
+ ├── __init__.py # Exportação pública da classe Idiomas
131
+ └── nucleo.py # Gerenciador INI, menu suspenso e janela Translate
132
+ ```
133
+
134
+ ---
135
+
136
+ ## 📝 Licença
137
+
138
+ Este projeto é de uso livre para projetos pessoais e comerciais.
@@ -0,0 +1 @@
1
+ from .nucleo import Idiomas
@@ -0,0 +1,664 @@
1
+ import configparser
2
+ import os
3
+ import tkinter as tk
4
+ from tkinter import ttk, messagebox
5
+ import customtkinter as ctk
6
+
7
+
8
+ class Idiomas:
9
+ """
10
+ Plug-in Plug & Play para CustomTkinter:
11
+ - Captura automática de título, labels, botões, checkboxes, switches, CTkEntry e CTkTabview
12
+ - Função auxiliar `lang.t("Texto dinâmico")` para mensagens em tempo de execução
13
+ - Menu suspenso arredondado com engrenagem ⚙️
14
+ - Janela Translate pré-preenchida para traduzir apenas o que você souber
15
+ """
16
+
17
+ def __init__(self, janela: ctk.CTk, idioma_principal: str, arquivo="app.ini"):
18
+ if not idioma_principal or not idioma_principal.strip():
19
+ raise ValueError(
20
+ "Você deve definir 'idioma_principal' (ex: 'Português (Brasil)' ou 'English')."
21
+ )
22
+
23
+ self.janela = janela
24
+ self.idioma_principal = idioma_principal.strip()
25
+ self.arquivo = os.path.abspath(arquivo)
26
+ self.ultima_modificacao = 0
27
+ self.menu_popup = None
28
+
29
+ # {chave: (widget, propriedade)}
30
+ self.mapa_widgets = {}
31
+
32
+ self.config = configparser.ConfigParser(interpolation=None)
33
+ self.config.optionxform = str
34
+
35
+ if os.path.exists(self.arquivo):
36
+ self.recarregar()
37
+ else:
38
+ self.config["Config"] = {"idioma": self.idioma_principal}
39
+
40
+ if self.idioma_principal not in self.config:
41
+ self.config.add_section(self.idioma_principal)
42
+
43
+ self._injetar_barra_superior()
44
+ self.janela.after(100, self._inicializar_captura)
45
+
46
+ def _inicializar_captura(self):
47
+ if os.path.exists(self.arquivo):
48
+ self.recarregar()
49
+
50
+ if self.idioma_principal not in self.config:
51
+ self.config.add_section(self.idioma_principal)
52
+
53
+ eh_ingles = (
54
+ "english" in self.idioma_principal.lower()
55
+ or "en" == self.idioma_principal.lower()
56
+ )
57
+ if "_lang_label" not in self.config[self.idioma_principal]:
58
+ self.config[self.idioma_principal]["_lang_label"] = (
59
+ "Language:" if eh_ingles else "Linguagem:"
60
+ )
61
+ if "_translate_btn" not in self.config[self.idioma_principal]:
62
+ self.config[self.idioma_principal]["_translate_btn"] = (
63
+ "Translate" if eh_ingles else "Traduzir"
64
+ )
65
+
66
+ # 1. Título da janela
67
+ titulo_atual = self.janela.title()
68
+ if titulo_atual:
69
+ self.mapa_widgets["00_titulo"] = (self.janela, "title")
70
+ if "00_titulo" not in self.config[self.idioma_principal]:
71
+ self.config[self.idioma_principal]["00_titulo"] = titulo_atual
72
+
73
+ # 2. Varre todos os widgets da janela (incluindo CTkTabview e CTkEntry)
74
+ contador = 1
75
+ for widget in self._listar_todos_widgets(self.janela):
76
+ if self._pertence_a_barra_topo(
77
+ widget
78
+ ) or self._pertence_a_tabview_interno(widget):
79
+ continue
80
+
81
+ if isinstance(widget, ctk.CTkTabview):
82
+ for (
83
+ nome_aba,
84
+ btn_aba,
85
+ ) in widget._segmented_button._buttons_dict.items():
86
+ chave = f"{contador:02d}"
87
+ self.mapa_widgets[chave] = (btn_aba, "tab")
88
+ if chave not in self.config[self.idioma_principal]:
89
+ self.config[self.idioma_principal][chave] = nome_aba
90
+ contador += 1
91
+ continue
92
+
93
+ if isinstance(widget, ctk.CTkEntry):
94
+ placeholder = widget.cget("placeholder_text")
95
+ if placeholder and placeholder.strip():
96
+ chave = f"{contador:02d}"
97
+ self.mapa_widgets[chave] = (widget, "placeholder")
98
+ if chave not in self.config[self.idioma_principal]:
99
+ self.config[self.idioma_principal][chave] = placeholder
100
+ contador += 1
101
+ continue
102
+
103
+ texto_widget = self._obter_texto_widget(widget)
104
+ if texto_widget and texto_widget.strip():
105
+ chave = f"{contador:02d}"
106
+ self.mapa_widgets[chave] = (widget, "text")
107
+ if chave not in self.config[self.idioma_principal]:
108
+ self.config[self.idioma_principal][chave] = texto_widget
109
+ contador += 1
110
+
111
+ self.salvar()
112
+ self.aplicar_idioma_na_tela()
113
+ self._iniciar_monitoramento()
114
+
115
+ # --- FUNÇÃO PARA TEXTOS DINÂMICOS (messagebox, alertas, textos pós-clique) ---
116
+ def t(self, texto_original: str, **kwargs) -> str:
117
+ """
118
+ Registra automaticamente mensagens dinâmicas no .ini e retorna a tradução.
119
+ Exemplo: messagebox.showinfo("Aviso", lang.t("Arquivo salvo com sucesso!"))
120
+ """
121
+ if not texto_original:
122
+ return ""
123
+
124
+ if self.idioma_principal not in self.config:
125
+ self.config.add_section(self.idioma_principal)
126
+
127
+ # Procura se esse texto dinâmico já foi registrado antes
128
+ chave_encontrada = None
129
+ for k, v in self.config[self.idioma_principal].items():
130
+ if k.startswith("msg_") and v == texto_original:
131
+ chave_encontrada = k
132
+ break
133
+
134
+ # Se ainda não existe no .ini, cria uma chave msg_01, msg_02...
135
+ if not chave_encontrada:
136
+ msgs_existentes = [
137
+ k
138
+ for k in self.config[self.idioma_principal].keys()
139
+ if k.startswith("msg_")
140
+ ]
141
+ chave_encontrada = f"msg_{len(msgs_existentes) + 1:02d}"
142
+ self.config[self.idioma_principal][chave_encontrada] = (
143
+ texto_original
144
+ )
145
+ self.salvar()
146
+
147
+ idioma_ativo = self.get_config("idioma", self.idioma_principal)
148
+ resultado = self.config.get(
149
+ idioma_ativo, chave_encontrada, fallback=texto_original
150
+ )
151
+ if not resultado.strip():
152
+ resultado = texto_original
153
+
154
+ return resultado.format(**kwargs) if kwargs else resultado
155
+
156
+ # Alias caso prefira escrever lang.traduzir("...")
157
+ traduzir = t
158
+
159
+ def _listar_todos_widgets(self, container):
160
+ lista = []
161
+ for filho in container.winfo_children():
162
+ if isinstance(filho, ctk.CTkToplevel):
163
+ continue
164
+ lista.append(filho)
165
+ lista.extend(self._listar_todos_widgets(filho))
166
+ return lista
167
+
168
+ def _pertence_a_barra_topo(self, widget):
169
+ atual = widget
170
+ while atual is not None:
171
+ if atual == self.barra_topo:
172
+ return True
173
+ atual = atual.master
174
+ return False
175
+
176
+ def _pertence_a_tabview_interno(self, widget):
177
+ if isinstance(widget.master, ctk.CTkSegmentedButton) and isinstance(
178
+ widget.master.master, ctk.CTkTabview
179
+ ):
180
+ return True
181
+ return False
182
+
183
+ def _obter_texto_widget(self, widget):
184
+ tipos_suportados = (
185
+ ctk.CTkLabel,
186
+ ctk.CTkButton,
187
+ ctk.CTkCheckBox,
188
+ ctk.CTkRadioButton,
189
+ ctk.CTkSwitch,
190
+ )
191
+ if isinstance(widget, tipos_suportados):
192
+ try:
193
+ return widget.cget("text")
194
+ except Exception:
195
+ return None
196
+ return None
197
+
198
+ def aplicar_idioma_na_tela(self):
199
+ idioma_ativo = self.get_config("idioma", self.idioma_principal)
200
+
201
+ for chave, (widget, prop) in self.mapa_widgets.items():
202
+ if not widget.winfo_exists():
203
+ continue
204
+
205
+ texto_original = self.config.get(
206
+ self.idioma_principal, chave, fallback=""
207
+ )
208
+ texto_final = self.config.get(
209
+ idioma_ativo, chave, fallback=texto_original
210
+ )
211
+ if not texto_final.strip():
212
+ texto_final = texto_original
213
+
214
+ if prop == "title":
215
+ self.janela.title(texto_final)
216
+ elif prop == "text":
217
+ widget.configure(text=texto_final)
218
+ elif prop == "placeholder":
219
+ widget.configure(placeholder_text=texto_final)
220
+ elif prop == "tab":
221
+ widget.configure(text=texto_final)
222
+
223
+ def _injetar_barra_superior(self):
224
+ self.barra_topo = ctk.CTkFrame(
225
+ self.janela, fg_color="transparent", height=36
226
+ )
227
+ self.barra_topo.pack(side="top", fill="x", padx=8, pady=(6, 0))
228
+
229
+ self.btn_engrenagem = ctk.CTkButton(
230
+ self.barra_topo,
231
+ text="⚙️",
232
+ width=34,
233
+ height=34,
234
+ corner_radius=8,
235
+ font=("Segoe UI Emoji", 15),
236
+ fg_color="transparent",
237
+ hover_color=("#E2E2E2", "#2F2F2F"),
238
+ command=self._alternar_menu,
239
+ )
240
+ self.btn_engrenagem.pack(side="right")
241
+
242
+ def _alternar_menu(self):
243
+ if self.menu_popup is not None and self.menu_popup.winfo_exists():
244
+ self._fechar_menu()
245
+ return
246
+ self._abrir_menu()
247
+
248
+ def _fechar_menu(self, event=None):
249
+ if self.menu_popup is not None and self.menu_popup.winfo_exists():
250
+ self.menu_popup.destroy()
251
+ self.menu_popup = None
252
+
253
+ def _abrir_menu(self):
254
+ popup = ctk.CTkToplevel(self.janela)
255
+ popup.overrideredirect(True)
256
+ popup.attributes("-topmost", True)
257
+ self.menu_popup = popup
258
+
259
+ cor_chave = "#000001"
260
+ popup.configure(fg_color=cor_chave)
261
+ try:
262
+ popup.wm_attributes("-transparentcolor", cor_chave)
263
+ except tk.TclError:
264
+ pass
265
+
266
+ card = ctk.CTkFrame(
267
+ popup,
268
+ corner_radius=12,
269
+ border_width=1,
270
+ border_color=("#CCCCCC", "#3E3E42"),
271
+ fg_color=("#F9F9F9", "#252526"),
272
+ )
273
+ card.pack(fill="both", expand=True, padx=2, pady=2)
274
+
275
+ lbl_titulo = ctk.CTkLabel(
276
+ card,
277
+ text=self.texto("_lang_label"),
278
+ font=("Segoe UI", 11, "bold"),
279
+ text_color=("#6E6E73", "#9A9A9E"),
280
+ anchor="w",
281
+ )
282
+ lbl_titulo.pack(fill="x", padx=14, pady=(10, 4))
283
+
284
+ idioma_atual = self.get_config("idioma", self.idioma_principal)
285
+ idiomas = [s for s in self.config.sections() if s != "Config"]
286
+
287
+ for lang in idiomas:
288
+ ativo = lang == idioma_atual
289
+ prefixo = "✓ " if ativo else " "
290
+ btn_lang = ctk.CTkButton(
291
+ card,
292
+ text=f"{prefixo}{lang}",
293
+ anchor="w",
294
+ height=30,
295
+ corner_radius=7,
296
+ font=("Segoe UI", 12, "bold" if ativo else "normal"),
297
+ fg_color=("#E5F1FB", "#1F6AA5") if ativo else "transparent",
298
+ text_color=("#005A9E", "#FFFFFF")
299
+ if ativo
300
+ else ("#1D1D1F", "#E5E5E7"),
301
+ hover_color=("#D6E8F8", "#2B79B8")
302
+ if ativo
303
+ else ("#EAEAEA", "#333337"),
304
+ command=lambda l=lang: self._selecionar_idioma(l),
305
+ )
306
+ btn_lang.pack(fill="x", padx=6, pady=1)
307
+
308
+ separador = ctk.CTkFrame(
309
+ card, height=1, fg_color=("#DCDCDC", "#3A3A3D")
310
+ )
311
+ separador.pack(fill="x", padx=10, pady=6)
312
+
313
+ btn_traduzir = ctk.CTkButton(
314
+ card,
315
+ text=f"🌐 {self.texto('_translate_btn')}",
316
+ anchor="w",
317
+ height=32,
318
+ corner_radius=7,
319
+ font=("Segoe UI", 12),
320
+ fg_color="transparent",
321
+ text_color=("#1D1D1F", "#E5E5E7"),
322
+ hover_color=("#EAEAEA", "#333337"),
323
+ command=self._abrir_tradutor_do_menu,
324
+ )
325
+ btn_traduzir.pack(fill="x", padx=6, pady=(0, 8))
326
+
327
+ popup.update_idletasks()
328
+ largura_menu = max(195, popup.winfo_reqwidth())
329
+ altura_menu = popup.winfo_reqheight()
330
+
331
+ btn_x = self.btn_engrenagem.winfo_rootx()
332
+ btn_y = self.btn_engrenagem.winfo_rooty()
333
+ btn_w = self.btn_engrenagem.winfo_width()
334
+ btn_h = self.btn_engrenagem.winfo_height()
335
+
336
+ pos_x = (btn_x + btn_w) - largura_menu
337
+ pos_y = btn_y + btn_h + 4
338
+
339
+ popup.geometry(f"{largura_menu}x{altura_menu}+{pos_x}+{pos_y}")
340
+ popup.focus_force()
341
+ popup.bind("<FocusOut>", self._verificar_perda_foco)
342
+ popup.bind("<Escape>", self._fechar_menu)
343
+
344
+ def _verificar_perda_foco(self, event=None):
345
+ if self.menu_popup is None or not self.menu_popup.winfo_exists():
346
+ return
347
+ foco_atual = self.janela.focus_get()
348
+ if foco_atual is None or not str(foco_atual).startswith(
349
+ str(self.menu_popup)
350
+ ):
351
+ self._fechar_menu()
352
+
353
+ def _selecionar_idioma(self, novo_idioma):
354
+ self._fechar_menu()
355
+ self.set_config("idioma", novo_idioma)
356
+ self.aplicar_idioma_na_tela()
357
+
358
+ def _abrir_tradutor_do_menu(self):
359
+ self._fechar_menu()
360
+ JanelaTradutor(self.janela, self)
361
+
362
+ def _iniciar_monitoramento(self):
363
+ if self.arquivo_foi_modificado():
364
+ try:
365
+ self.recarregar()
366
+ self.aplicar_idioma_na_tela()
367
+ except configparser.Error:
368
+ pass
369
+ self.janela.after(1000, self._iniciar_monitoramento)
370
+
371
+ def recarregar(self):
372
+ self.config.clear()
373
+ self.config.read(self.arquivo, encoding="utf-8")
374
+ self.ultima_modificacao = os.path.getmtime(self.arquivo)
375
+
376
+ def arquivo_foi_modificado(self):
377
+ if not os.path.exists(self.arquivo):
378
+ return False
379
+ return os.path.getmtime(self.arquivo) != self.ultima_modificacao
380
+
381
+ def texto(self, chave):
382
+ idioma = self.config.get(
383
+ "Config", "idioma", fallback=self.idioma_principal
384
+ )
385
+ original = self.config.get(
386
+ self.idioma_principal, chave, fallback=f"[{chave}]"
387
+ )
388
+ res = self.config.get(idioma, chave, fallback=original)
389
+ return res if res.strip() else original
390
+
391
+ def get_config(self, chave, padrao=""):
392
+ return self.config.get("Config", chave, fallback=padrao)
393
+
394
+ def set_config(self, chave, valor):
395
+ self.config["Config"][chave] = str(valor)
396
+ self.salvar()
397
+
398
+ def salvar(self):
399
+ with open(self.arquivo, "w", encoding="utf-8") as f:
400
+ self.config.write(f)
401
+ self.ultima_modificacao = os.path.getmtime(self.arquivo)
402
+
403
+
404
+ class JanelaTradutor(ctk.CTkToplevel):
405
+ """
406
+ Janela integrada de tradução:
407
+ Já preenche todos os campos com os textos do idioma selecionado,
408
+ permitindo traduzir apenas o que você souber e manter o resto original.
409
+ """
410
+
411
+ def __init__(self, master, gerenciador: Idiomas):
412
+ super().__init__(master)
413
+ self.ini = gerenciador
414
+ self.dados_traducao = {}
415
+ self.chave_atual = None
416
+
417
+ self.title("Translate")
418
+ self.geometry("820x520")
419
+ self.grab_set()
420
+
421
+ self._criar_topo()
422
+ self._criar_tabela()
423
+ self._criar_rodape()
424
+ self._atualizar_tabela()
425
+
426
+ def _criar_topo(self):
427
+ frame_topo = ctk.CTkFrame(self)
428
+ frame_topo.pack(fill="x", padx=12, pady=(12, 6))
429
+
430
+ idiomas = [s for s in self.ini.config.sections() if s != "Config"]
431
+ idioma_padrao = idiomas[0] if idiomas else self.ini.idioma_principal
432
+
433
+ frame_base = ctk.CTkFrame(frame_topo, fg_color="transparent")
434
+ frame_base.pack(side="left", padx=10, pady=8)
435
+ ctk.CTkLabel(frame_base, text="Select Your Language (Base):").pack(
436
+ anchor="w"
437
+ )
438
+ self.combo_base = ctk.CTkOptionMenu(
439
+ frame_base,
440
+ values=idiomas,
441
+ command=lambda e: self._atualizar_tabela(base=e),
442
+ width=180,
443
+ )
444
+ atual = self.ini.get_config("idioma", idioma_padrao)
445
+ self.combo_base.set(atual if atual in idiomas else idioma_padrao)
446
+ self.combo_base.pack()
447
+
448
+ frame_novo = ctk.CTkFrame(frame_topo, fg_color="transparent")
449
+ frame_novo.pack(side="left", padx=10, pady=8)
450
+ ctk.CTkLabel(frame_novo, text="Write or Select Target Language:").pack(
451
+ anchor="w"
452
+ )
453
+ self.entry_novo_idioma = ctk.CTkComboBox(
454
+ frame_novo,
455
+ values=idiomas,
456
+ command=lambda e: self._atualizar_tabela(alvo=e),
457
+ width=190,
458
+ )
459
+ self.entry_novo_idioma.set("")
460
+ self.entry_novo_idioma.bind(
461
+ "<Return>", lambda _: self._atualizar_tabela()
462
+ )
463
+ self.entry_novo_idioma.bind(
464
+ "<FocusOut>", lambda _: self._atualizar_tabela()
465
+ )
466
+ self.entry_novo_idioma.pack()
467
+
468
+ frame_btns = ctk.CTkFrame(frame_topo, fg_color="transparent")
469
+ frame_btns.pack(side="right", padx=10, pady=8)
470
+
471
+ ctk.CTkButton(
472
+ frame_btns,
473
+ text="Save Language",
474
+ width=130,
475
+ command=self._salvar_idioma,
476
+ ).pack(side="left", padx=5)
477
+
478
+ ctk.CTkButton(
479
+ frame_btns,
480
+ text="Copy to Clipboard",
481
+ width=140,
482
+ fg_color="#3B8ED0",
483
+ command=self._copiar_ini,
484
+ ).pack(side="left", padx=5)
485
+
486
+ def _criar_tabela(self):
487
+ frame_tabela = ctk.CTkFrame(self)
488
+ frame_tabela.pack(fill="both", expand=True, padx=12, pady=6)
489
+
490
+ style = ttk.Style()
491
+ style.theme_use("default")
492
+ style.configure("Treeview", rowheight=26, font=("Segoe UI", 10))
493
+ style.configure("Treeview.Heading", font=("Segoe UI", 10, "bold"))
494
+
495
+ colunas = ("id", "original", "traducao")
496
+ self.tree = ttk.Treeview(
497
+ frame_tabela, columns=colunas, show="headings", selectmode="browse"
498
+ )
499
+ self.tree.heading("id", text="ID")
500
+ self.tree.heading("original", text="Base Language String")
501
+ self.tree.heading("traducao", text="Your Language String")
502
+
503
+ self.tree.column("id", width=80, anchor="center")
504
+ self.tree.column("original", width=350, anchor="w")
505
+ self.tree.column("traducao", width=350, anchor="w")
506
+
507
+ scroll = ttk.Scrollbar(
508
+ frame_tabela, orient="vertical", command=self.tree.yview
509
+ )
510
+ self.tree.configure(yscrollcommand=scroll.set)
511
+
512
+ self.tree.pack(side="left", fill="both", expand=True)
513
+ scroll.pack(side="right", fill="y")
514
+
515
+ self.tree.bind("<<TreeviewSelect>>", self._ao_selecionar_linha)
516
+
517
+ def _criar_rodape(self):
518
+ frame_rodape = ctk.CTkFrame(self)
519
+ frame_rodape.pack(fill="x", padx=12, pady=(6, 12))
520
+
521
+ ctk.CTkLabel(
522
+ frame_rodape,
523
+ text="To go to another line, use Up/Down arrows or click on the table above:",
524
+ font=("Segoe UI", 11),
525
+ ).pack(anchor="w", padx=10, pady=(6, 2))
526
+
527
+ frame_caixas = ctk.CTkFrame(frame_rodape, fg_color="transparent")
528
+ frame_caixas.pack(fill="x", padx=10, pady=(0, 10))
529
+
530
+ self.txt_original = ctk.CTkTextbox(frame_caixas, height=85, width=380)
531
+ self.txt_original.pack(side="left", fill="both", expand=True, padx=(0, 6))
532
+ self.txt_original.configure(state="disabled")
533
+
534
+ self.txt_traducao = ctk.CTkTextbox(frame_caixas, height=85, width=380)
535
+ self.txt_traducao.pack(
536
+ side="right", fill="both", expand=True, padx=(6, 0)
537
+ )
538
+ self.txt_traducao.bind("<KeyRelease>", self._ao_digitar_traducao)
539
+ self.txt_traducao.bind("<Up>", lambda e: self._mover_selecao(-1))
540
+ self.txt_traducao.bind("<Down>", lambda e: self._mover_selecao(1))
541
+
542
+ def _atualizar_tabela(self, base=None, alvo=None):
543
+ """
544
+ Preenche a coluna da direita com as traduções já existentes do idioma alvo;
545
+ se o idioma alvo ainda não existir ou faltar alguma linha, já preenche com
546
+ o texto do idioma base para você editar apenas o que souber!
547
+ """
548
+ self.ini.recarregar()
549
+ self.tree.delete(*self.tree.get_children())
550
+ self.dados_traducao.clear()
551
+
552
+ idioma_base = base if base else self.combo_base.get()
553
+ idioma_alvo = alvo if alvo else self.entry_novo_idioma.get().strip()
554
+
555
+ if idioma_base not in self.ini.config:
556
+ return
557
+
558
+ for chave, valor_base in self.ini.config[idioma_base].items():
559
+ # Começa preenchido com o texto base
560
+ valor_trad = valor_base
561
+ # Se o idioma alvo já existe e tem texto não-vazio nessa chave, usa ele
562
+ if (
563
+ idioma_alvo in self.ini.config
564
+ and chave in self.ini.config[idioma_alvo]
565
+ ):
566
+ existente = self.ini.config[idioma_alvo][chave]
567
+ if existente and existente.strip():
568
+ valor_trad = existente
569
+
570
+ self.dados_traducao[chave] = valor_trad
571
+ self.tree.insert(
572
+ "", "end", iid=chave, values=(chave, valor_base, valor_trad)
573
+ )
574
+
575
+ filhos = self.tree.get_children()
576
+ if filhos:
577
+ self.tree.selection_set(filhos[0])
578
+ self._ao_selecionar_linha()
579
+
580
+ def _ao_selecionar_linha(self, event=None):
581
+ selecionado = self.tree.selection()
582
+ if not selecionado:
583
+ return
584
+
585
+ self.chave_atual = selecionado[0]
586
+ valores = self.tree.item(self.chave_atual, "values")
587
+
588
+ self.txt_original.configure(state="normal")
589
+ self.txt_original.delete("1.0", "end")
590
+ self.txt_original.insert("1.0", valores[1])
591
+ self.txt_original.configure(state="disabled")
592
+
593
+ self.txt_traducao.delete("1.0", "end")
594
+ self.txt_traducao.insert(
595
+ "1.0", self.dados_traducao.get(self.chave_atual, "")
596
+ )
597
+
598
+ def _ao_digitar_traducao(self, event=None):
599
+ if not self.chave_atual:
600
+ return
601
+ texto = self.txt_traducao.get("1.0", "end-1c").replace("\n", "\\n")
602
+ self.dados_traducao[self.chave_atual] = texto
603
+
604
+ valor_original = self.tree.item(self.chave_atual, "values")[1]
605
+ self.tree.item(
606
+ self.chave_atual, values=(self.chave_atual, valor_original, texto)
607
+ )
608
+
609
+ def _mover_selecao(self, direcao):
610
+ filhos = self.tree.get_children()
611
+ if not filhos or not self.chave_atual:
612
+ return "break"
613
+ idx = filhos.index(self.chave_atual) + direcao
614
+ if 0 <= idx < len(filhos):
615
+ self.tree.selection_set(filhos[idx])
616
+ self.tree.see(filhos[idx])
617
+ self._ao_selecionar_linha()
618
+ return "break"
619
+
620
+ def _gerar_bloco_ini(self, nome_idioma):
621
+ linhas = [f"[{nome_idioma}]"]
622
+ for chave, trad in self.dados_traducao.items():
623
+ valor_original = self.tree.item(chave, "values")[1]
624
+ texto_final = trad if trad.strip() else valor_original
625
+ linhas.append(f"{chave} = {texto_final}")
626
+ return "\n".join(linhas)
627
+
628
+ def _salvar_idioma(self):
629
+ novo_idioma = self.entry_novo_idioma.get().strip()
630
+ if not novo_idioma or novo_idioma == "Config":
631
+ messagebox.showwarning(
632
+ "Aviso", "Digite um nome válido para o idioma.", parent=self
633
+ )
634
+ return
635
+
636
+ if novo_idioma not in self.ini.config:
637
+ self.ini.config.add_section(novo_idioma)
638
+
639
+ for chave, trad in self.dados_traducao.items():
640
+ valor_original = self.tree.item(chave, "values")[1]
641
+ texto_final = trad if trad.strip() else valor_original
642
+ self.ini.config[novo_idioma][chave] = texto_final
643
+
644
+ self.ini.set_config("idioma", novo_idioma)
645
+ idiomas_atualizados = [
646
+ s for s in self.ini.config.sections() if s != "Config"
647
+ ]
648
+ self.combo_base.configure(values=idiomas_atualizados)
649
+ self.entry_novo_idioma.configure(values=idiomas_atualizados)
650
+ self.ini.aplicar_idioma_na_tela()
651
+ messagebox.showinfo(
652
+ "Sucesso", f"Idioma '{novo_idioma}' salvo e aplicado!", parent=self
653
+ )
654
+
655
+ def _copiar_ini(self):
656
+ nome = self.entry_novo_idioma.get().strip() or "Novo_Idioma"
657
+ bloco = self._gerar_bloco_ini(nome)
658
+ self.clipboard_clear()
659
+ self.clipboard_append(bloco)
660
+ messagebox.showinfo(
661
+ "Copiado",
662
+ "Tradução copiada para a área de transferência!",
663
+ parent=self,
664
+ )
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctk-idiomas
3
+ Version: 0.1.0
4
+ Summary: Sistema Plug & Play de idiomas e tradução visual para CustomTkinter
5
+ Author: Lucas Gabriel da Costa
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: customtkinter>=5.0.0
9
+
10
+ # 🌐 ctk-idiomas
11
+
12
+ Sistema **Plug & Play** de internacionalização (i18n), troca de idiomas em tempo real e editor visual de traduções para aplicativos feitos com **CustomTkinter**.
13
+
14
+ Com apenas **uma linha de código**, o `ctk-idiomas` injeta um menu suspenso moderno no topo da sua janela, captura automaticamente os textos da interface, gera o arquivo `.ini` e permite que você ou qualquer usuário crie novas traduções sem mexer no código-fonte.
15
+
16
+ ---
17
+
18
+ ## ✨ Funcionalidades
19
+
20
+ - **Zero Configuração de Layout:** Injeta automaticamente um botão de engrenagem (`⚙️`) no canto superior direito da janela com menu suspenso arredondado.
21
+ - **Varredura Automática de Widgets:** Detecta e traduz sozinho:
22
+ - Título da janela (`app.title`)
23
+ - Textos de `CTkLabel`, `CTkButton`, `CTkCheckBox`, `CTkRadioButton` e `CTkSwitch`
24
+ - Campos de entrada `CTkEntry` (`placeholder_text`)
25
+ - Títulos das abas de `CTkTabview`
26
+ - **Mensagens Dinâmicas (`lang.t`):** Registra e traduz textos exibidos apenas em tempo de execução (como `messagebox` ou textos pós-clique), com suporte a variáveis (`{nome}`).
27
+ - **Editor Visual Integrado (`Translate`):** Janela embutida com tabela lado a lado, navegação por teclado (`↑` / `↓`), pré-preenchimento inteligente (mantém o texto original nas frases não traduzidas) e exportação para a área de transferência.
28
+ - **Hot Reload em Tempo Real:** Monitora o arquivo `app.ini` em segundo plano — editou e salvou no bloco de notas, a interface atualiza na hora sem reiniciar o app.
29
+
30
+ ---
31
+
32
+ ## 🛠️ Ferramentas e Tecnologias Utilizadas
33
+
34
+ - **[Python 3.8+](https://python.org):** Linguagem base do projeto.
35
+ - **[CustomTkinter](https://github.com):** Construção dos componentes visuais modernos, janelas auxiliares e menu suspenso estilizado.
36
+ - **`configparser` (Biblioteca Padrão):** Leitura, escrita e gerenciamento estruturado dos arquivos `.ini` em UTF-8.
37
+ - **`tkinter` / `ttk` (Biblioteca Padrão):** Renderização da tabela de tradução (`Treeview`) e controle de eventos de foco/teclado.
38
+ - **`setuptools`:** Empacotamento padrão PEP 621 via `pyproject.toml` para instalação universal via `pip`.
39
+
40
+ ---
41
+
42
+ ## 📦 Instalação
43
+
44
+ ### Instalação local (Modo Desenvolvimento)
45
+ Clone ou baixe este repositório, abra o terminal na pasta raiz (`ctk_idiomas/`) e execute:
46
+
47
+ ```bash
48
+ pip install -e .
49
+ ```
50
+
51
+ ### Instalação via GitHub
52
+ Em qualquer projeto ou computador, instale diretamente pelo terminal:
53
+
54
+ ```bash
55
+ pip install https://github.com/LucasGabrieldaCosta123/ctk-idiomas/archive/refs/heads/main.zip
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 🚀 Como Usar
61
+
62
+ Basta importar `Idiomas` e iniciá-lo logo após criar a janela principal, informando o **`idioma_principal`** em que o aplicativo foi escrito:
63
+
64
+ ```python
65
+ from tkinter import messagebox
66
+ import customtkinter as ctk
67
+ from ctk_idiomas import Idiomas
68
+
69
+ app = ctk.CTk()
70
+ app.title("Meu Aplicativo")
71
+ app.geometry("460x320")
72
+
73
+ # 1. Inicializa o sistema de idiomas (injeta o botão ⚙️ automaticamente)
74
+ lang = Idiomas(app, idioma_principal="Português (Brasil)")
75
+
76
+ # 2. Crie sua interface normalmente
77
+ abas = ctk.CTkTabview(app)
78
+ abas.pack(fill="both", expand=True, padx=15, pady=10)
79
+
80
+ aba_inicio = abas.add("Início")
81
+ aba_sobre = abas.add("Sobre")
82
+
83
+ entrada = ctk.CTkEntry(aba_inicio, placeholder_text="Digite seu nome")
84
+ entrada.pack(pady=(20, 10), fill="x", padx=20)
85
+
86
+ def ao_clicar():
87
+ nome = entrada.get() or "Visitante"
88
+ # 3. Use lang.t() para mensagens dinâmicas em tempo de execução
89
+ messagebox.showinfo(
90
+ lang.t("Aviso"),
91
+ lang.t("Olá, {nome}! Bem-vindo ao sistema.", nome=nome)
92
+ )
93
+
94
+ ctk.CTkButton(aba_inicio, text="Confirmar", command=ao_clicar).pack(pady=10)
95
+ ctk.CTkLabel(aba_sobre, text="Versão 1.0").pack(pady=30)
96
+
97
+ app.mainloop()
98
+ ```
99
+
100
+ ---
101
+
102
+ ## ⚙️ Como Funciona por Dentro
103
+
104
+ 1. **Captura Pós-Montagem (`after`):** Assim que o aplicativo inicia, o `Idiomas` aguarda a montagem dos widgets na tela e percorre recursivamente toda a árvore de componentes (`winfo_children`), mapeando cada widget para um ID numérico (`01`, `02`, `03`...).
105
+ 2. **Geração do `app.ini`:** Na primeira execução, cria o arquivo `app.ini` em UTF-8 na pasta do projeto contendo a seção `[Config]` e a seção do idioma principal definida pelo desenvolvedor.
106
+ 3. **Fallback Seguro:** Caso um usuário crie uma tradução parcial (traduzindo apenas algumas frases), o sistema preenche automaticamente as linhas restantes com o texto do idioma base, evitando campos vazios ou erros na interface.
107
+ 4. **Monitoramento de Arquivo:** A cada `1000ms`, verifica o *timestamp* (`os.path.getmtime`) do `app.ini`. Se houver alteração externa no disco, relê o arquivo e reaplica os textos na janela instantaneamente.
108
+
109
+ ---
110
+
111
+ ## 📄 Exemplo do `app.ini` Gerado
112
+
113
+ ```ini
114
+ [Config]
115
+ idioma = Português (Brasil)
116
+
117
+ [Português (Brasil)]
118
+ _lang_label = Linguagem:
119
+ _translate_btn = Traduzir
120
+ 00_titulo = Meu Aplicativo
121
+ 01 = Início
122
+ 02 = Sobre
123
+ 03 = Digite seu nome
124
+ 04 = Confirmar
125
+ 05 = Versão 1.0
126
+ msg_01 = Aviso
127
+ msg_02 = Olá, {nome}! Bem-vindo ao sistema.
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 📁 Estrutura do Pacote
133
+
134
+ ```text
135
+ ctk_idiomas/
136
+ ├── pyproject.toml # Metadados e dependências do pacote
137
+ ├── README.md # Documentação do projeto
138
+ └── ctk_idiomas/
139
+ ├── __init__.py # Exportação pública da classe Idiomas
140
+ └── nucleo.py # Gerenciador INI, menu suspenso e janela Translate
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 📝 Licença
146
+
147
+ Este projeto é de uso livre para projetos pessoais e comerciais.
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ ctk_idiomas/__init__.py
4
+ ctk_idiomas/nucleo.py
5
+ ctk_idiomas.egg-info/PKG-INFO
6
+ ctk_idiomas.egg-info/SOURCES.txt
7
+ ctk_idiomas.egg-info/dependency_links.txt
8
+ ctk_idiomas.egg-info/requires.txt
9
+ ctk_idiomas.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ customtkinter>=5.0.0
@@ -0,0 +1 @@
1
+ ctk_idiomas
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ctk-idiomas"
7
+ version = "0.1.0"
8
+ description = "Sistema Plug & Play de idiomas e tradução visual para CustomTkinter"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ authors = [
12
+ { name = "Lucas Gabriel da Costa" }
13
+ ]
14
+ dependencies = [
15
+ "customtkinter>=5.0.0"
16
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+