diff --git a/README.md b/README.md index f9c450b..5a4b835 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,6 @@

English中文

-

📺 YouTube video: https://youtu.be/lo6Ee_k_zG0

- > [!Important] > Donate / sponsor to help the project grow and become better! (https://patreon.com/axorax) @@ -18,15 +16,16 @@ - [Why and how?](#-why-and-how) - [App Preview](#-app-preview) - [Features](#-features) +- [Made with TkForge](#-made-with-tkforge) - [Usage Guide](#-usage-guide) - [Available names](#-available-names) - [Names that have unique features](#-names-that-have-unique-features) - [CLI Usage Guide](#-cli-usage-guide) -- [Add the CLI exe to the environment variables in Windows](#-add-the-cli-exe-to-the-environment-variables-in-windows) +- [Add CLI exe to environment variables in Windows](#-add-cli-exe-to-environment-variables-in-windows) ## ❓ Why and how? -Something like this has already been done by ParthJadhav with Tkinter Designer but I liked the concept and wanted to make something similar if not better from scratch. TkForge interacts with the Figma API to get the details of the file and turns that into code. First, it gets the file data and converts it into a format that only has the necessary details then that is converted into code. This project took me a lot longer than I had anticipated. +Something like this has already been done by ParthJadhav with Tkinter Designer but I liked the concept and wanted to make something similar if not better from scratch. TkForge interacts with the Figma API to get the details of the file and turns that into code. You can check my video on it to learn more :) ## 💻 App Preview @@ -39,6 +38,11 @@ Something like this has already been done by ParthJadhav with Tkinter Designer b - Support for placeholder text - Support for more than one frame - Automatically sets foreground to either black or white depending on the background (not always accurate) +- Image hashing + +## 🐍 Made with TkForge + +Join our [Discord server](https://discord.gg/nKUFghjXQu) and post/view apps made with TkForge! ## ✨ Usage Guide @@ -145,30 +149,10 @@ tkforge "my_id" "my_token" tkforge "my_id" "my_token" . ``` -## 🪟 Add the CLI exe to the environment variables in Windows - -Step 1: Create a folder with any name like "tkforge" - -Step 2: Put the TkForge CLI exe file in that folder - -Step 3: Rename the exe from `tkforge-cli.exe` to `tkforge.exe` - -Step 4: Copy the path name. - -Example copied path name: `C:\Users\PC\Downloads\tkforge` - -Do not copy the path for the ".exe", copy the path for the folder. - -If the path name has quotes on both sides like this `"C:\Users\PC\Downloads\tkforge-cli"`, then make sure to remove the quotes. - -Step 5: Open the "Edit the system environment variables" app - -Step 6: Click on "Environment Variables..." then on "System variables" click "Path" - -Step 7: Then, click "Edit" then "New" and paste the path +## 🪟 Add CLI exe to environment variables in Windows -Step 8: Click "Ok", "Ok" and "Ok" and you should be done! +https://github.com/user-attachments/assets/f87c6df1-3f9a-442c-a28b-a947b7c7b1f4 --- -

Support me on PatreonCheck out my socials

\ No newline at end of file +

Support me on PatreonCheck out my socials

diff --git a/README_ru.md b/README_ru.md new file mode 100644 index 0000000..2d13f7d --- /dev/null +++ b/README_ru.md @@ -0,0 +1,160 @@ +

TkForge Logo

+ +

TkForge

+ +

Перетаскивание в Figma для легкого создания Python GUI

+ +

Проголосовать на Product HuntПожертвовать

+ +

English中文Русский

+ +> [!IMPORTANT] +> Пожертвуйте или спонсируйте проект, чтобы помочь ему расти и становиться лучше! (https://patreon.com/axorax) +> +> Translated by SiresMacro (@siresmacro in Discord) + +## 📰 Содержание + +- [Почему и как?](#-почему-и-как) +- [Предварительный просмотр приложения](#-предварительный-просмотр-приложения) +- [Возможности](#-возможности) +- [Сделано с TkForge](#-сделано-с-tkforge) +- [Руководство по использованию](#-руководство-по-использованию) +- [Доступные имена](#-доступные-имена) +- [Имена с уникальными возможностями](#-имена-с-уникальными-возможностями) +- [Руководство по использованию CLI](#-руководство-по-использованию-cli) +- [Добавление CLI exe в переменные среды в Windows](#-добавление-cli-exe-в-переменные-среды-в-windows) + +## ❓ Почему и как? + +Что-то подобное уже было создано ParthJadhav с Tkinter Designer, но мне понравилась концепция, и я хотел создать что-то похожее, если не лучше, с нуля. TkForge взаимодействует с API Figma, чтобы получить детали файла и превратить их в код. Вы можете посмотреть мое видео об этом, чтобы узнать больше :) + +## 💻 Предварительный просмотр приложения + +![TkForge Application Preview](./preview.png) + +## 🔥 Возможности + +- Очень простое в использовании +- Создание GUI методом перетаскивания +- Поддержка текста-заглушки +- Поддержка более одного фрейма +- Автоматически устанавливает передний план в черный или белый цвет в зависимости от фона (не всегда точно) +- Хеширование изображений + +## 🐍 Сделано с TkForge + +Присоединяйтесь к нашему [Discord серверу](https://discord.gg/nKUFghjXQu) и размещайте/просматривайте приложения, созданные с помощью TkForge! + +## ✨ Руководство по использованию + +Сначала вам нужно скачать исполняемый файл со страницы релизов. Затем вам нужно создать токен Figma и скопировать URL вашего проекта. После этого откройте приложение, вставьте токен и URL вашего проекта в приложение и нажмите кнопку, чтобы начать магию! 🪄 + +Убедитесь, что ваш проект Figma использует фреймы. TkForge превращает содержимое внутри фреймов в работающие GUI и игнорирует все, что не находится во фрейме. + +В проекте Figma убедитесь, что добавили правильные имена для всех ваших элементов. + +## 🧿 Доступные имена + +| Имя | Элемент Tkinter | 2-й аргумент (текст после пробела) | +| -------------------------------------- | ---------------- | ---------------------------------- | +| `text` (можно также назвать как угодно) | canvas text | - | +| `button` | button | - | +| `image` | canvas image | имя файла изображения | +| `textbox` | entry | текст-заглушка | +| `textarea` | text | текст-заглушка | +| `spinbox` | spinbox | - | +| `rectangle` | canvas rectangle | - | +| `circle` | canvas circle | - | +| `oval` | canvas oval | - | +| `line` | canvas line | - | +| `label` | label | - | +| `scale` | scale | FROM TO ORIENT | +| `listbox` (читайте ниже перед использованием) | listbox | - | + +Если любой элемент начинается с этих имен, то он будет считаться соответствующим элементом Tkinter. Например; `rectangle 1`, `rectangle`, `Rectangle`, `RecTanGle 69` все будут считаться прямоугольником. Регистр не имеет значения. + +## 💎 Имена с уникальными возможностями + +### • `label` + +Вы можете использовать label вместо text, если хотите изменить этот текст позже. + +### • `image` + +Вы можете задать имя для файла изображения таким образом: `image myImage`. Изображение будет создано с именем `myImage.png` + +### • `circle` и `oval` + +Oval и circle работают одинаково, поэтому вы можете использовать любой из них. + +### • `circle`, `oval`, `rectangle` и `line` + +Поддерживаются цвет обводки и ширина обводки, что означает, что если вы добавите обводку к ним в Figma, они появятся с этой обводкой и шириной обводки в дизайне Tkinter тоже. + +### • `textarea` и `textbox` + +Чтобы добавить текст-заглушку, просто включите его после имени элемента и пробела. Например, `textbox Hello world` или `textarea Hello world`. Чтобы установить цвет текста-заглушки, добавьте `placeholder_fg="цвет_здесь"`. Пример: + +```python +textbox_1 = TkForge_Entry( + placeholder="Пример кода", + placeholder_fg="#fff" +) +``` + +Используйте `textbox_1.is_placeholder(False)`, чтобы убедиться, что вставленный текст не наследует цвет заглушки. Получите текст-заглушку с помощью `textbox_1.get_placeholder()`. Текст-заглушка может потребовать дополнительной обработки для различных ситуаций. + +### • `scale` + +Для значений from, to и orient элемента scale вы можете поместить их после имени один за другим, разделенные пробелами. Например; если я хочу scale с from=10, to=50 и orient=HORIZONTAL, то я могу написать `scale 10 50` или `scale 10 50 HORIZONTAL`, а если я хочу orient=VERTICAL, то `scale 10 50 VERTICAL` + +### • `listbox` + +Рекомендуется избегать использования `listbox`, поскольку он искажает высоту и ширину на несколько пикселей. Единицы Figma работают неправильно, поэтому мне пришлось разделить их на конкретные числа, чтобы приблизиться к внешнему виду Figma. + +## 🔮 Руководство по использованию CLI + +Если вы хотите запустить его из файла Python, используйте `python tkforge.py ВАШИ_АРГУМЕНТЫ_ЗДЕСЬ` + +Вы можете использовать `tkforge --help`, чтобы получить команду помощи. Если вы используете файл Python, используйте `python tkforge.py --help` + +Вам может потребоваться использовать `./tkforge.exe` или что-то подобное, если вы не добавили исполняемый файл CLI в переменные среды. + +Вот некоторые примеры использования: + +### Синтаксис на основе флагов + +```sh +tkforge --id "my_id" --token "my_token" --out ./app +``` + +Вы можете использовать любую из команд ниже, если хотите, чтобы вывод был в текущем каталоге: + +```sh +tkforge --id "my_id" --token "my_token" + +tkforge --id "my_id" --token "my_token" --out . +``` + +### Позиционный синтаксис + +```sh +tkforge "my_id" "my_token" output_path +``` + +Вы можете использовать любую из команд ниже, если хотите, чтобы вывод был в текущем каталоге: + +```sh +tkforge "my_id" "my_token" + +tkforge "my_id" "my_token" . +``` + +## 🪟 Добавление CLI exe в переменные среды в Windows + +https://github.com/user-attachments/assets/f87c6df1-3f9a-442c-a28b-a947b7c7b1f4 + +--- + +

Поддержите меня на PatreonПосмотрите мои социальные сети

diff --git a/README_zh.md b/README_zh.md index 26bc863..6bec6aa 100644 --- a/README_zh.md +++ b/README_zh.md @@ -20,6 +20,7 @@ - [为什么?](#-为什么) - [应用程序预览](#-应用程序预览) - [特点](#-特点) +- [使用 TkForge 制作](#-使用-tkforge-制作) - [使用指南](#-使用指南) - [可用名称](#-可用名称) - [具有独特特征的名字](#-具有独特特征的名字) @@ -42,6 +43,10 @@ ParthJadhav 已经用 Tkinter Designer 完成了类似的工作,但我喜欢 - 支持多个框架 - 根据背景自动将前景设置为黑色或白色(不一定准确) +## 🐍 使用 TkForge 制作 + +加入我们的 [Discord 服务器](https://discord.gg/nKUFghjXQu) 并发布/查看使用 TkForge 制作的应用程序! + ## ✨ 使用指南 首先,您需要从发布页面下载可执行文件。然后,您需要创建一个 Figma 标记并复制项目的网址。然后,打开应用程序,将令牌和项目的网址粘贴到应用程序中,点击按钮即可启动魔法!🪄 @@ -149,27 +154,7 @@ tkforge "my_id" "my_token" . ## 🪟 在 Windows 环境变量中添加 CLI exe -步骤 1:创建一个任意名称的文件夹,如 "tkforge"。 - -步骤 2:将 TkForge CLI exe 文件放到该文件夹中 - -第 3 步:将 exe 文件从 `tkforge-cli.exe` 重命名为 `tkforge.exe` 。 - -第 4 步:复制路径名。 - -复制路径名示例: `C:\Users\PC\Downloads\tkforge` - -不要复制".exe "的路径,复制文件夹的路径。 - -如果路径名两边都有引号,如`"C:\Users\PC\Downloads\tkforge-cli"`,则确保去掉引号。 - -第 5 步:打开 "编辑系统环境变量 "应用程序 - -第 6 步:点击 "环境变量...",然后在 "系统变量 "中点击 "路径 - -第 7 步:然后点击 "编辑",再点击 "新建 "并粘贴路径 - -第 8 步:点击 "确定"、"确定 "和 "确定",然后就完成了! +https://github.com/user-attachments/assets/f87c6df1-3f9a-442c-a28b-a947b7c7b1f4 --- diff --git a/core.py b/core.py index 2d213bf..a6f217a 100644 --- a/core.py +++ b/core.py @@ -1,8 +1,11 @@ import os +import hashlib import requests import threading from utils import rgb_to_hex, get_foreground_color +HASH_IMAGES = True + def get_file(file, token): response = requests.get(f"https://api.figma.com/v1/files/{file}", headers={'X-FIGMA-TOKEN': token}) @@ -11,6 +14,11 @@ def get_file(file, token): else: return response.status_code, response.text +downloaded_images = {} + +def get_image_hash(image_content): + return hashlib.sha256(image_content).hexdigest() + def download_image(file, id, name, token, out=None, frame=None): response = requests.get(f"https://api.figma.com/v1/images/{file}", headers={'X-FIGMA-TOKEN': token}, params={'ids': id}) @@ -32,13 +40,20 @@ def download_image(file, id, name, token, out=None, frame=None): image_response = requests.get(image_url) if image_response.status_code == 200: + image_content = image_response.content + if HASH_IMAGES: + image_hash = get_image_hash(image_content) + + if image_hash in downloaded_images: + return downloaded_images[image_hash] + with open(file_path, 'wb') as f: - f.write(image_response.content) + f.write(image_content) - if frame is not None: - return os.path.join(f'frame_{frame}', file_name).replace('\\', '/') - else: - return file_name + if HASH_IMAGES: + downloaded_images[image_hash] = os.path.join(f'frame_{frame}', file_name).replace('\\', '/') if frame else file_name + + return os.path.join(f'frame_{frame}', file_name).replace('\\', '/') if frame else file_name else: print("Failed to download the image.") else: @@ -58,8 +73,6 @@ def parse_file(file, token, download_images=True, out=None): try: frames = result['document']['children'][0]['children'] frame_count = 1 if len(frames) > 1 else 0 - # import json - # print(json.dumps(frames, indent=4, sort_keys=True)) def parse_frame(frame, frame_count): nonlocal output diff --git a/gui.py b/gui.py index e41ed72..a96b6a1 100644 --- a/gui.py +++ b/gui.py @@ -8,7 +8,7 @@ import webbrowser import tkinter as tk from tk import tk_code -from utils import extract_figma_id, check_for_updates +from utils import extract_figma_id, has_update from tkinter import filedialog, messagebox def load_asset(path): @@ -273,10 +273,9 @@ def select_outpath(): donate_button.place(x=371, y=446, width=343, height=34) -try: - exec(check_for_updates()) -except: - print("No updates!") +update = has_update() +if update == True: + messagebox.showinfo('New update!', "Update your version of TkForge to get the latest features! https://github.com/axorax/tkforge/releases") root.resizable(False, False) root.mainloop() diff --git a/info.py b/info.py deleted file mode 100644 index 79e1960..0000000 --- a/info.py +++ /dev/null @@ -1 +0,0 @@ -messagebox.showinfo('New update!', "Update your version of TkForge to get the latest features! https://github.com/axorax/tkforge/releases") diff --git a/info_cli.py b/info_cli.py deleted file mode 100644 index 6d069d2..0000000 --- a/info_cli.py +++ /dev/null @@ -1,3 +0,0 @@ -print("New update!") -print("Update your version of TkForge to get the latest features!") -print("https://github.com/axorax/tkforge/releases") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 29ea4f0..34faccd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,10 +5,7 @@ colorama==0.4.6 idna==3.7 packaging==24.1 pefile==2024.8.26 -<<<<<<< HEAD -pillow==10.4.0 -======= ->>>>>>> 250f915 (fix: Include pyinstaller) +pillow==11.0.0 pyinstaller==6.10.0 pyinstaller-hooks-contrib==2024.8 pywin32-ctypes==0.2.3 diff --git a/tkforge.py b/tkforge.py index 96c494f..db79c83 100644 --- a/tkforge.py +++ b/tkforge.py @@ -2,7 +2,7 @@ import argparse from tk import tk_code from colorama import Fore, init -from utils import extract_figma_id, check_for_updates, VERSION +from utils import extract_figma_id, has_update, VERSION init(autoreset=True) @@ -37,11 +37,11 @@ def main(): if args.update: try: - update = check_for_updates(False) - if update == "": + update = has_update() + if update == False: print(Fore.GREEN + "No updates!") else: - exec(update) + print("New update!\nUpdate your version of TkForge to get the latest features!\nhttps://github.com/axorax/tkforge/releases") except: print(Fore.RED + "Update check failed!") return diff --git a/utils.py b/utils.py index 6e13b7e..1f7f0cf 100644 --- a/utils.py +++ b/utils.py @@ -5,7 +5,7 @@ VERSION = "2.1.1" BASE_URL = "https://raw.githubusercontent.com/Axorax/tkforge/refs/heads/main/" -def check_for_updates(gui_info = True): +def has_update(): try: global VERSION response = requests.get(f"{BASE_URL}VERSION.txt") @@ -14,13 +14,11 @@ def check_for_updates(gui_info = True): version_tuple = tuple(map(int, VERSION.split('.'))) online_version_tuple = tuple(map(int, online_version.split('.'))) if online_version_tuple > version_tuple: - response = requests.get(f"{BASE_URL}{"info" if gui_info else "info_cli"}.py") - response.raise_for_status() - return response.text + return True else: - return "" - except requests.RequestException as e: - return "" + return False + except requests.RequestException as _: + return False def rgb_to_hex(r, g, b): return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"