diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..df45c41 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +patreon: axorax \ No newline at end of file diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..e7a6fd8 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,25 @@ +name: Check + +on: + push: + +jobs: + check-files: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Check if required files exist or not + id: check_files + run: | + missing_files=() + [ ! -f README.md ] && missing_files+=("README.md") + [ ! -f requirements.txt ] && missing_files+=("requirements.txt") + + if [ ${#missing_files[@]} -ne 0 ]; then + echo "❌ Missing files: ${missing_files[@]}" + exit 1 + else + echo "✅ All required files exist." + fi \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b64948e --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Folders + +*env/ +dist/ +test/ +build/ +TkForge/ +__pycache__/ +chocolatey-package/ + +# Files + +*.txt +!VERSION.txt +*.spec +main.py \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ceca6e9 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,22 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery +- Personal attacks +- Trolling or insulting/derogatory comments +- Public or private harassment +- Publishing other's private information, such as physical or electronic addresses, without explicit permission +- Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.2.0, available at https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..cd1cec9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,10 @@ +# Guidelines for contributing to TkForge + +Your pull request will not be accepted if it falls into any one of the categories below: + +- Just a refactor of the code +- Only changing some text either in the comments or in any markdown file +- A negligible improvement like trimming a string +- A useless change +- Hampers the user experience or complicates things for the user too much +- Contains anything offensive to a certain group of people diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ea4b73e --- /dev/null +++ b/README.md @@ -0,0 +1,178 @@ +

TkForge Logo

+ +

TkForge

+ +

Drag & drop in Figma to create a Python GUI with ease

+ +

Upvote on Product HuntDonate

+ +

English中文

+ +

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

+ +> [!Important] +> Donate / sponsor to help the project grow and become better! (https://patreon.com/axorax) + +## 📰 Table of Contents + +- [Why and how?](#-why-and-how) +- [App Preview](#-app-preview) +- [Features](#-features) +- [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) + +## ❓ 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. + +## 💻 App Preview + +![TkForge Application Preview](./preview.png) + +## 🔥 Features + +- Super easy to use +- Drag and drop GUI maker +- 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) + +## ✨ Usage Guide + +First, you need to download the executable from the releases page. Next, you need to create a Figma token and copy the url of your project. Then, open the app and paste the token and url of your project into the app and click the button to start the magic! 🪄 + +Make sure your Figma project uses frames. TkForge turns the content inside frames into working GUI's and ignores anything that is not in a frame. + +In the Figma project, make sure to add proper names for all of your elements. + +## 🧿 Available names + +| Name | Tkinter Element | 2nd Argument (text after space) | +| -------------------------------------- | ---------------- | ------------------------------- | +| `text` (you can also name it anything) | canvas text | - | +| `button` | button | - | +| `image` | canvas image | image file name | +| `textbox` | entry | placeholder text | +| `textarea` | text | placeholder text | +| `spinbox` | spinbox | - | +| `rectangle` | canvas rectangle | - | +| `circle` | canvas circle | - | +| `oval` | canvas oval | - | +| `line` | canvas line | - | +| `label` | label | - | +| `scale` | scale | FROM TO ORIENT | +| `listbox` (Read below before using) | listbox | - | + +If any element starts with these names then it will be considered as that Tkinter element. For example; `rectangle 1`, `rectangle`, `Rectangle`, `RecTanGle 69` will all be considered as a rectangle. The capitalization does not matter. + +## 💎 Names that have unique features + +### • `label` + +You can use label instead of text if you want to change that text later on. + +### • `image` + +You can set a name for the image file like this `image myImage`. The image will be created with the name `myImage.png` + +### • `circle` and `oval` + +Oval and circle act in the same way so you can use either one of those. + +### • `circle`, `oval`, `rectangle` and `line` + +Stroke color and stroke width are supported that means if you add a stroke to them in Figma, they will appear with that stroke and stroke width in the Tkinter design as well. + +### • `textarea` and `textbox` + +To add placeholder text, simply include it after the element name and a space. For instance, `textbox Hello world` or `textarea Hello world`. To set the placeholder text color, add `placeholder_fg="color_here"`. Example: + +```python +textbox_1 = TkForge_Entry( + placeholder="Code Example", + placeholder_fg="#fff" +) +``` + +Use `textbox_1.is_placeholder(False)` to ensure inserted text doesn't inherit the placeholder color. Retrieve the placeholder text with `textbox_1.get_placeholder()`. Placeholder text may require additional handling for various situations. + +### • `scale` + +For the from, to and orient values of the scale element you can put them after the name one after the other separated by spaces. For example; if I want a scale that has from=10, to=50 and orient=HORIZONTAL then I can do `scale 10 50` or `scale 10 50 HORIZONTAL` and if I want orient=VERTICAL then `scale 10 50 VERTICAL` + +### • `listbox` + +It's recommended to avoid using `listbox` as it distorts height and width by a few pixels. Figma units don't work properly so I had to divide them by specific numbers to approximate the Figma look. + +## 🔮 CLI Usage Guide + +If you want to run it from the Python file then use `python tkforge.py YOUR_ARGUMENTS_HERE` + +You can use `tkforge --help` to get the help command. If you're using the Python file, use `python tkforge.py --help` + +You may need to use `./tkforge.exe` or something similar if you haven't added the CLI executable to the environment variables. + +Here are some example usages: + +### Flag-based Syntax + +``` +tkforge --id my_id --token my_token --out ./app +``` + +You can use any one of the command below if you want the output to be in the current directory: + +``` +tkforge --id my_id --token my_token --out . +``` + +``` +tkforge --id my_id --token my_token +``` + +### Positional Syntax + +``` +tkforge my_id my_token output_path +``` + +You can use any one of the command below if you want the output to be in the current directory: + +``` +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 + +Step 8: Click "Ok", "Ok" and "Ok" and you should be done! + +--- + +

Support me on PatreonCheck out my socials

\ No newline at end of file diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000..45915c1 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,180 @@ +

TkForge 徽标

+ +

TkForge

+ +

在 Figma 中拖放,轻松创建 Python 图形用户界面

+ +

在 Product Hunt 上点赞捐赠

+ +

English中文

+ +

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

+ +> [!Important] +> 捐款/赞助,帮助项目发展壮大! (https://patreon.com/axorax) +> +> 这只是一个粗略的翻译,可能并不准确。 + +## 📰 目录 + +- [为什么?](#-为什么) +- [应用程序预览](#-应用程序预览) +- [特点](#-特点) +- [使用指南](#-使用指南) +- [可用名称](#-可用名称) +- [具有独特特征的名字](#-具有独特特征的名字) +- [CLI 使用指南](#-cli-使用指南) +- [在 Windows 环境变量中添加 CLI exe](#-在-windows-环境变量中添加-cli-exe) + +## ❓ 为什么? + +ParthJadhav 已经用 Tkinter Designer 完成了类似的工作,但我喜欢这个概念,并想从头开始做一个类似的东西,甚至做得更好。TkForge 与 Figma API 交互,获取文件的详细信息,并将其转化为代码。首先,它获取文件数据并将其转换为只包含必要细节的格式,然后再将其转换为代码。这个项目花费的时间比我预计的要长很多。 + +## 💻 应用程序预览 + +![TkForge 应用程序预览](./preview.png) + +## 🔥 特点 + +- 超级易用 +- 拖放式图形用户界面制作工具 +- 支持占位符文本 +- 支持多个框架 +- 根据背景自动将前景设置为黑色或白色(不一定准确) + +## ✨ 使用指南 + +首先,您需要从发布页面下载可执行文件。然后,您需要创建一个 Figma 标记并复制项目的网址。然后,打开应用程序,将令牌和项目的网址粘贴到应用程序中,点击按钮即可启动魔法!🪄 + +确保您的 Figma 项目使用框架。TkForge 会将框架内的内容转化为可运行的图形用户界面,并忽略任何不在框架内的内容。 + +在 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 元素。例如,"矩形 1"、"矩形"、"矩形"、"RecTanGle 69 "都将被视为矩形。大小写并不重要。 + +## 💎 具有独特特征的名字 + +### • `label` + +如果以后想更改文本,可以使用标签代替文本。 + +### • `image` + +您可以为图像文件设置一个名称,例如 `image myImage`。创建的图像将命名为 `myImage.png`。 + +### • `circle` and `oval` + +椭圆形和圆形的作用相同,因此可以任选其一。 + +### • `circle`, `oval`, `rectangle` and `line` + +支持描边颜色和描边宽度,这意味着如果您在 Figma 中为它们添加了描边,它们在 Tkinter 设计中也会以相同的描边和描边宽度显示。 + +### • `textarea` and `textbox` + +要添加占位符文本,只需在元素名称后加上空格即可。例如,`textbox Hello world` 或 `textarea Hello world`。要设置占位符文本的颜色,可添加 `placeholder_fg="color_here"`。例如 + +```python +textbox_1 = TkForge_Entry( + placeholder="Code Example", + placeholder_fg="#fff" +) +``` + +使用 `textbox_1.is_placeholder(False)` 来确保插入的文本不会继承占位符的颜色。使用 `textbox_1.get_placeholder()` 获取占位符文本。在各种情况下,占位符文本可能需要额外处理。 + +### • `scale` + +对于标尺元素的 from、to 和 orient 值,可以将它们一个接一个地放在名称后面,中间用空格隔开。例如,如果我想要一个 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 YOUR_ARGUMENTS_HERE` 。 + +您可以使用 `tkforge --help` 获取帮助命令。如果您使用的是 Python 文件,请使用 `python tkforge.py --help` 。 + +如果您没有在环境变量中添加 CLI 可执行文件,则可能需要使用 `./tkforge.exe` 或类似命令。 + +下面是一些使用示例: + +### 基于标志的语法 + +``` +tkforge --id my_id --token my_token --out ./app +``` + +如果希望在当前目录下输出,可以使用以下任意一条命令: + +``` +tkforge --id my_id --token my_token --out . +``` + +``` +tkforge --id my_id --token my_token +``` + +### 位置语法 + +``` +tkforge my_id my_token output_path +``` + +如果希望在当前目录下输出,可以使用以下任意一条命令: + +``` +tkforge my_id my_token . +``` + +``` +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 步:点击 "确定"、"确定 "和 "确定",然后就完成了! + +--- + +

在 Patreon 上支持我查看我的社交网站

\ No newline at end of file diff --git a/VERSION.txt b/VERSION.txt new file mode 100644 index 0000000..50aea0e --- /dev/null +++ b/VERSION.txt @@ -0,0 +1 @@ +2.1.0 \ No newline at end of file diff --git a/assets/backgrounds/1.png b/assets/backgrounds/1.png new file mode 100644 index 0000000..54e8c39 Binary files /dev/null and b/assets/backgrounds/1.png differ diff --git a/assets/backgrounds/2.png b/assets/backgrounds/2.png new file mode 100644 index 0000000..bb06055 Binary files /dev/null and b/assets/backgrounds/2.png differ diff --git a/assets/backgrounds/3.png b/assets/backgrounds/3.png new file mode 100644 index 0000000..98e95a0 Binary files /dev/null and b/assets/backgrounds/3.png differ diff --git a/assets/backgrounds/4.png b/assets/backgrounds/4.png new file mode 100644 index 0000000..0d57979 Binary files /dev/null and b/assets/backgrounds/4.png differ diff --git a/assets/backgrounds/5.png b/assets/backgrounds/5.png new file mode 100644 index 0000000..7617430 Binary files /dev/null and b/assets/backgrounds/5.png differ diff --git a/assets/icon.ico b/assets/icon.ico new file mode 100644 index 0000000..95d4a4b Binary files /dev/null and b/assets/icon.ico differ diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000..7175852 Binary files /dev/null and b/assets/icon.png differ diff --git a/assets/image_1.png b/assets/image_1.png new file mode 100644 index 0000000..1ca5fbb Binary files /dev/null and b/assets/image_1.png differ diff --git a/assets/image_2.png b/assets/image_2.png new file mode 100644 index 0000000..b6e9fc8 Binary files /dev/null and b/assets/image_2.png differ diff --git a/assets/image_3.png b/assets/image_3.png new file mode 100644 index 0000000..c706273 Binary files /dev/null and b/assets/image_3.png differ diff --git a/assets/image_4.png b/assets/image_4.png new file mode 100644 index 0000000..890dec3 Binary files /dev/null and b/assets/image_4.png differ diff --git a/assets/image_5.png b/assets/image_5.png new file mode 100644 index 0000000..30a712a Binary files /dev/null and b/assets/image_5.png differ diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..9c85b92 --- /dev/null +++ b/build.bat @@ -0,0 +1,7 @@ +@echo off + +if "%1" == "cli" ( + pyinstaller --name="tkforge-cli" --onefile --strip --paths=env/Lib/site-packages tkforge.py --icon=assets/icon.png +) else ( + pyinstaller --name="TkForge" --onefile --strip --paths=env/Lib/site-packages --add-data="assets;assets" gui.py --noconsole --icon=assets/icon.png +) diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..b5d015f --- /dev/null +++ b/build.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +if [ "$1" == "cli" ]; then + pyinstaller --name="tkforge-cli" --onefile --strip --paths=env/Lib/site-packages tkforge.py --icon=assets/icon.png +else + pyinstaller --name="TkForge" --onefile --strip --paths=env/Lib/site-packages --add-data="assets:assets" gui.py --noconsole --icon=assets/icon.png +fi diff --git a/core.py b/core.py new file mode 100644 index 0000000..2d213bf --- /dev/null +++ b/core.py @@ -0,0 +1,190 @@ +import os +import requests +import threading +from utils import rgb_to_hex, get_foreground_color + +def get_file(file, token): + response = requests.get(f"https://api.figma.com/v1/files/{file}", headers={'X-FIGMA-TOKEN': token}) + + if response.status_code == 200: + return response.json() + else: + return response.status_code, response.text + +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}) + + if response.status_code == 200: + json_data = response.json() + image_url = json_data.get('images', {}).get(id) + + if image_url: + if frame is not None: + folder_path = os.path.join(out, 'TkForge/assets', f'frame_{frame}') if out else os.path.join('TkForge/assets', f'frame_{frame}') + else: + folder_path = os.path.join(out, 'TkForge/assets') if out else 'TkForge/assets' + + if not os.path.exists(folder_path): + os.makedirs(folder_path) + + file_name = f'{name}.png' + file_path = os.path.join(folder_path, file_name) + image_response = requests.get(image_url) + + if image_response.status_code == 200: + with open(file_path, 'wb') as f: + f.write(image_response.content) + + if frame is not None: + return os.path.join(f'frame_{frame}', file_name).replace('\\', '/') + else: + return file_name + else: + print("Failed to download the image.") + else: + print("No image URL found for the specified ID.") + else: + print("Failed to retrieve image URL.") + + return None + +def parse_file(file, token, download_images=True, out=None): + output = [] + result = get_file(file, token) + + if isinstance(result, tuple): + return [] + + 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 + parsed = [] + image_count = 0 + entry_placeholder = False + text_placeholder = False + + for i in frame['children']: + if 'absoluteBoundingBox' in i: + bounds = i['absoluteBoundingBox'] + else: + bounds = i['absoluteRenderBounds'] + + items = ["image", "button", "label", "scale", "listbox", "textbox", "textarea", "rectangle", "spinbox", "circle", "oval", "line"] + type = i['name'].split(' ', 1)[0].lower() + type = type if type in items else "text" + + i['type'] = type + i['x'] = abs(int(frame['absoluteBoundingBox']['x']) - int(bounds['x'])) + i['y'] = abs(int(frame['absoluteBoundingBox']['y']) - int(bounds['y'])) + i['width'] = int(bounds['width']) + i['height'] = int(bounds['height']) + i['background'] = None + + bg_color = i.get('backgroundColor') or \ + (i.get('background', [{}])[0].get('color') if i.get('background') else None) or \ + (i.get('fills', [{}])[0].get('color') if i.get('fills') else "#000000") + + if bg_color and bg_color != "#000000": + i['background'] = rgb_to_hex(bg_color['r'], bg_color['g'], bg_color['b']) + fg = get_foreground_color(bg_color['r'], bg_color['g'], bg_color['b']) + + if fg == i['background']: + i['foreground'] = '#ffffff' if fg == '#000000' else '#000000' if fg == '#ffffff' else fg + else: + i['foreground'] = fg + else: + i['background'] = "#000000" + i['foreground'] = "#FFFFFF" + + def download(name): + nonlocal i + image = download_image(file, i['id'], name, token, out, frame_count) if frame_count > 0 else download_image(file, i['id'], name, token, out) + + if image: + i['image'] = image + else: + i['image'] = None + + if (i.get('strokes') and not i.get('strokes') == []): + stroke_color = i.get('strokes', [{}])[0].get('color') + i['stroke_color'] = rgb_to_hex(stroke_color['r'], stroke_color['g'], stroke_color['b']) + + if type in ['text', 'label']: + i['text'] = i.get('characters', '').replace('\n', '\\n') + style = i.get('style', {}) + i['font'] = style.get('fontFamily', 'Default Font') + i['font_size'] = int(style.get('fontSize', 12)) + + elif type == 'image': + parts = i['name'].split(' ') + name = " ".join(parts[1:]) + if not name.replace(' ', '') == '': + download(name) + else: + image_count += 1 + download(str(image_count)) + + elif type == 'scale': + scale = i['name'].split(' ') + i['from'] = int(scale[1]) + i['to'] = int(scale[2]) + i['orient'] = scale[3] if len(scale) > 3 else "HORIZONTAL" + + elif type in ['textbox', 'textarea']: + parts = i['name'].split(' ') + placeholder = " ".join(parts[1:]) + + if not placeholder.replace(' ', '') == '': + i['placeholder'] = placeholder + + if type == 'textbox': + entry_placeholder = True + + elif type == 'textarea': + text_placeholder = True + + elif type == 'button' and download_images: + image_count += 1 + download(image_count) + + parsed.append(i) + + frame_bg = frame.get('backgroundColor') or \ + (frame.get('background', [{}])[0].get('color') if frame.get('background') else None) or \ + (frame.get('fills', [{}])[0].get('color') if frame.get('fills') else None) + + if frame_bg: + frame_bg = rgb_to_hex(frame_bg['r'], frame_bg['g'], frame_bg['b']) + else: + frame_bg = "No background color specified" + + output.append([parsed, [ + int(frame['absoluteBoundingBox']['width']), + int(frame['absoluteBoundingBox']['height']), + frame_bg, + result['name'].replace('\n', '\\n'), + frame_count, + entry_placeholder, + text_placeholder + ]]) + + threads = [] + for frame in frames: + if frame["type"] == "FRAME": + thread = threading.Thread(target=parse_frame, args=(frame, frame_count,)) + threads.append(thread) + thread.start() + frame_count = frame_count + 1; + + for thread in threads: + thread.join() + + except KeyError as e: + print(f"KeyError: {str(e)} - likely due to missing keys in JSON response") + + return output diff --git a/gui.py b/gui.py new file mode 100644 index 0000000..e41ed72 --- /dev/null +++ b/gui.py @@ -0,0 +1,282 @@ +# Code generated by TkForge +# Donate to support TkForge! + +import os +import sys +import random +import threading +import webbrowser +import tkinter as tk +from tk import tk_code +from utils import extract_figma_id, check_for_updates +from tkinter import filedialog, messagebox + +def load_asset(path): + base = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) + assets = os.path.join(base, "assets") + return os.path.join(assets, path) + +root = tk.Tk() +root.geometry("750x500") +root.configure(bg="#ffffff") +root.title("TkForge") +icon_image = tk.PhotoImage(file=load_asset("icon.png")) +root.iconphoto(True, icon_image) + +current_gui = "main" +main_gui = tk.Frame(root) +main_gui.pack(fill=tk.BOTH, expand=True) +progress_gui = tk.Frame(root) +progress_gui.pack_forget() + +placeholders = [ + "Your Figma token", + "Figma file URL or just ID", + "Output path or leave blank to use current directory" +] + +def toggle_gui(): + global current_gui + if current_gui == "main": + main_gui.pack_forget() + progress_gui.pack(fill=tk.BOTH, expand=True) + current_gui = "progress" + else: + progress_gui.pack_forget() + main_gui.pack(fill=tk.BOTH, expand=True) + current_gui = "main" + +# Canvas + +progress_canvas = tk.Canvas( + progress_gui, + bg = "#ffffff", + width = 750, + height = 500, + bd = 0, + highlightthickness = 0, + relief = "ridge" +) + +progress_canvas.place(x=0, y=0) + +main_canvas = tk.Canvas( + main_gui, + bg = "#ffffff", + width = 750, + height = 500, + bd = 0, + highlightthickness = 0, + relief = "ridge" +) + +main_canvas.place(x=0, y=0) + +# Layout + +background = tk.PhotoImage(file=load_asset(f"backgrounds/{random.randint(1, 5)}.png")) + +main_canvas.create_image(167, 250, image=background) + +progress_canvas.create_image(167, 250, image=background) + +progress_layout = tk.PhotoImage(file=load_asset("image_5.png")) + +progress_canvas.create_image(392, 253, image=progress_layout) + +main_layout = tk.PhotoImage(file=load_asset("image_1.png")) + +main_canvas.create_image(383, 253, image=main_layout) + +# Placeholder code + +class TkForge_Entry(tk.Entry): + def __init__(self, master=None, placeholder="Enter text", placeholder_fg='grey', **kwargs): + super().__init__(master, **kwargs) + + self.p, self.p_fg, self.fg = placeholder, placeholder_fg, self.cget("fg") + self.putp() + self.bind("", self.toggle) + self.bind("", self.toggle) + + def putp(self): + self.delete(0, tk.END) + self.insert(0, self.p) + self.config(fg=self.p_fg) + self.p_a = True + + def toggle(self, event): + if self.p_a: + self.delete(0, tk.END) + self.config(fg=self.fg) + self.p_a = False + elif not self.get(): self.putp() + + def get(self): return '' if self.p_a else super().get() + + def is_placeholder(self, b): + self.p_a = b + self.config(fg=self.p_fg if b == True else self.fg) + + def get_placeholder(self): return self.p + + +# Figma token input + +token_input = TkForge_Entry( + main_gui, + bd=0, + bg="#f5f5f5", + fg="#000", + highlightthickness=0, + placeholder=placeholders[0] +) + +token_input.place(x=376, y=109, width=331, height=28) + +# File URL input + +file_input = TkForge_Entry( + main_gui, + bd=0, + bg="#f5f5f5", + fg="#000", + highlightthickness=0, + placeholder=placeholders[1] +) + +file_input.place(x=376, y=191, width=331, height=28) + +# Output path textbox + +outpath_input = TkForge_Entry( + main_gui, + bd=0, + bg="#f5f5f5", + fg="#000", + highlightthickness=0, + placeholder=placeholders[2] +) + +outpath_input.place(x=376, y=272, width=299, height=28) + +# Generate code + +def clear_token_input(t=True): + token_input.delete(0, tk.END) + if t: + token_input.is_placeholder(True) + token_input.insert(0, token_input.get_placeholder()) + +def clear_file_input(t=True): + file_input.delete(0, tk.END) + if t: + file_input.is_placeholder(True) + file_input.insert(0, file_input.get_placeholder()) + +def generate(): + token = token_input.get().strip().replace(' ', '') + file = file_input.get().strip().replace(' ', '') + output = outpath_input.get() + + def generate_code_threaded(): + nonlocal token, file, output + if token == "" or token in placeholders: + clear_token_input(False) + token_input.is_placeholder(False) + token_input.insert(0, "THIS IS REQUIRED") + root.after(1500, clear_token_input) + return + + if file == "" or file in placeholders: + clear_file_input(False) + file_input.is_placeholder(False) + file_input.insert(0, "THIS IS REQUIRED") + root.after(1500, clear_file_input) + return + + if output == '': + if os.path.exists('TkForge'): + response = messagebox.askyesno("Directory Already Exists", "The folder 'TkForge' already exists. Do you want to override it?") + if not response: + return + else: + if os.path.exists(os.path.join(output, 'TkForge')): + response = messagebox.askyesno("Directory Already Exists", f"The folder 'TkForge' in the directory '{output}' already exists. Do you want to override it?") + if not response: + return + + toggle_gui() + code = tk_code(extract_figma_id(file), token, output) + + if code == None: + messagebox.showerror('Invalid token or file', 'The file ID, token or output path that you provided is invalid!') + toggle_gui() + elif code == True: + messagebox.showinfo('Success', 'Your code has been generated!') + toggle_gui() + + thread = threading.Thread(target=generate_code_threaded) + thread.start() + +# Generate button + +generate_button_image = tk.PhotoImage(file=load_asset("image_3.png")) + +generate_button = tk.Button( + main_gui, + image=generate_button_image, + relief="flat", + borderwidth=0, + highlightthickness=0, + command=generate +) + +generate_button.place(x=372, y=328, width=339, height=38) + +# Output path selection + +def select_outpath(): + path = filedialog.askdirectory() + if path: + outpath_input.delete(0, tk.END) + outpath_input.is_placeholder(False) + outpath_input.insert(0, path) + +# Output path button + +outpath_button_image = tk.PhotoImage(file=load_asset("image_2.png")) + +outpath_button = tk.Button( + main_gui, + image=outpath_button_image, + relief="flat", + borderwidth=0, + highlightthickness=0, + command=select_outpath +) + +outpath_button.place(x=685, y=273, width=24, height=27) + +# Donate button + +donate_button_image = tk.PhotoImage(file=load_asset("image_4.png")) + +donate_button = tk.Button( + main_gui, + image=donate_button_image, + relief="flat", + borderwidth=0, + highlightthickness=0, + command=lambda: webbrowser.open("https://www.patreon.com/axorax") +) + +donate_button.place(x=371, y=446, width=343, height=34) + +try: + exec(check_for_updates()) +except: + print("No updates!") + +root.resizable(False, False) +root.mainloop() diff --git a/info.py b/info.py new file mode 100644 index 0000000..79e1960 --- /dev/null +++ b/info.py @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..6d069d2 --- /dev/null +++ b/info_cli.py @@ -0,0 +1,3 @@ +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/preview.png b/preview.png new file mode 100644 index 0000000..c8749dc Binary files /dev/null and b/preview.png differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..29ea4f0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +altgraph==0.17.4 +certifi==2024.2.2 +charset-normalizer==3.3.2 +colorama==0.4.6 +idna==3.7 +packaging==24.1 +pefile==2024.8.26 +<<<<<<< HEAD +pillow==10.4.0 +======= +>>>>>>> 250f915 (fix: Include pyinstaller) +pyinstaller==6.10.0 +pyinstaller-hooks-contrib==2024.8 +pywin32-ctypes==0.2.3 +requests==2.31.0 +setuptools==74.1.2 +urllib3==2.2.1 diff --git a/tk.py b/tk.py new file mode 100644 index 0000000..6af7c16 --- /dev/null +++ b/tk.py @@ -0,0 +1,284 @@ +import threading +from core import parse_file +from utils import write_file + +def text(i): + return f''' +canvas.create_text( + {i['x']}, + {i['y']}, + anchor="nw", + text="{i['text']}", + fill="{i['background'] if i['background'] is not None else 'black'}", + font=("{i['font']}", {i['font_size']} * -1) +) +''' + +def button(i, c): + return f''' +button_{c}_image = tk.PhotoImage(file=load_asset("{i['image']}")) + +button_{c} = tk.Button( + image=button_{c}_image, + relief="flat", + borderwidth=0, + highlightthickness=0, + command=lambda: print("button_{c} has been pressed!") +) + +button_{c}.place(x={i['x']}, y={i['y']}, width={i['width']}, height={i['height']}) +''' + +def image(i, c): + return f''' +image_{c} = tk.PhotoImage(file=load_asset("{i['image']}")) + +canvas.create_image({int(i['x'] + i['width'] / 2)}, {int(i['y'] + i['height'] / 2)}, image=image_{c}) +''' + +def textbox(i, c, p=False): + s = f''',\n placeholder="{i['placeholder']}",''' if p else "," + return f''' +textbox_{c} = {"TkForge_Entry" if p else "tk.Entry"}( + bd=0, + bg="{i["background"]}", + fg="{i['foreground']}"{s} + insertbackground="{i['foreground']}", + highlightthickness=0 +) + +textbox_{c}.place(x={i["x"]}, y={i["y"]}, width={i["width"]}, height={i["height"]}) +''' + +def textarea(i, c, p=False): + s = f''',\n placeholder="{i['placeholder']}",''' if p else "," + return f''' +textarea_{c} = {"TkForge_Text" if p else "tk.Text"}( + bd=0, + bg="{i["background"]}", + fg="{i["foreground"]}"{s} + insertbackground="{i['foreground']}", + highlightthickness=0 +) + +textarea_{c}.place(x={i["x"]}, y={i["y"]}, width={i["width"]}, height={i["height"]}) +''' + +def spinbox(i, c): + return f''' +spinbox_{c} = tk.Spinbox() + +spinbox_{c}.place(x={i['x']}, y={i['y']}, width={i['width']}, height={i['height']}) +''' + +def rectangle(i): + o = f'''outline="{i['stroke_color']}", width="{i['strokeWeight']}"''' if not i['strokes'] == [] and i.get('stroke_color') else 'outline=""' + return f''' +canvas.create_rectangle({i['x']}, {i['y']}, {i['x'] + i['width']}, {i['y'] + i['height']}, fill='{i['background']}', {o}) +''' + +def oval(i): + o = f'''outline="{i['stroke_color']}", width="{i['strokeWeight']}"''' if not i['strokes'] == [] and i.get('stroke_color') else 'outline=""' + return f''' +canvas.create_oval({i['x']}, {i['y']}, {i['x'] + i['width']}, {i['y'] + i['height']}, fill="{i['background']}", {o}) +''' + +def line(i): + return f''' +canvas.create_line({i['x']}, {i['y']}, {i['x'] + i['width']}, {i['y'] + i['height']}, fill="{i['background']}", width={i['strokeWeight']}) +''' + +def label(i, c, b): + return f''' +label_{c} = tk.Label( + text="{i['text']}", + fg="{i['background']}", + bg="{b}", + font=("{i['font']}", {i['font_size']} * -1) +) + +label_{c}.place(x={i['x']}, y={i['y']}) +''' + +def scale(i, c): + return f''' +scale_{c} = tk.Scale( + from_={i['from']}, + to={i['to']}, + orient=tk.{i['orient']} +) + +scale_{c}.place(x={i['x']}, y={i['y']}) +''' + +def listbox(i, c): + return f''' +listbox_{c} = tk.Listbox(width={int(i['width'] / 6.1)}, height={int(i['height'] / 15.5)}) + +listbox_{c}.place(x={i['x']}, y={i['y']}) +''' + +elements = { + "text": text, + "button": button, + "image": image, + "textbox": textbox, + "textarea": textarea, + "spinbox": spinbox, + "rectangle": rectangle, + "circle": oval, + "oval": oval, + "line": line, + "label": label, + "scale": scale, + "listbox": listbox +} + +def tk_code(file, token, out=None): + counts = { + "button": 0, + "image": 0, + "textbox": 0, + "textarea": 0, + "spinbox": 0, + "label": 0, + "scale": 0, + "listbox": 0 + } + + parsed = parse_file(file, token, True, out) + multiple = False + + if parsed == [] or parsed == '[]': + return None + + if len(parsed) > 1: + multiple = True + + def generate_gui(data): + template = f'''# Code generated by TkForge +# Donate to support TkForge! + +import os +import sys +import tkinter as tk + +def load_asset(path): + base = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) + assets = os.path.join(base, "assets") + return os.path.join(assets, path) + +window = tk.Tk() +window.geometry("{data[1][0]}x{data[1][1]}") +window.configure(bg="{data[1][2]}") +window.title("{data[1][3]}") + +canvas = tk.Canvas( + window, + bg = "{data[1][2]}", + width = {data[1][0]}, + height = {data[1][1]}, + bd = 0, + highlightthickness = 0, + relief = "ridge" +) + +canvas.place(x=0, y=0) +''' + + if data[1][5]: + template += ''' +class TkForge_Entry(tk.Entry): + def __init__(self, master=None, placeholder="Enter text", placeholder_fg='grey', **kwargs): + super().__init__(master, **kwargs) + + self.p, self.p_fg, self.fg = placeholder, placeholder_fg, self.cget("fg") + self.putp() + self.bind("", self.toggle) + self.bind("", self.toggle) + + def putp(self): + self.delete(0, tk.END) + self.insert(0, self.p) + self.config(fg=self.p_fg) + self.p_a = True + + def toggle(self, event): + if self.p_a: + self.delete(0, tk.END) + self.config(fg=self.fg) + self.p_a = False + elif not self.get(): self.putp() + + def get(self): return '' if self.p_a else super().get() + + def is_placeholder(self, b): + self.p_a = b + self.config(fg=self.p_fg if b == True else self.fg) + + def get_placeholder(self): return self.p +''' + + if data[1][6]: + template += ''' +class TkForge_Text(tk.Text): + def __init__(self, master=None, placeholder="Enter text", placeholder_fg='grey', **kwargs): + super().__init__(master, **kwargs) + + self.p, self.p_fg, self.fg = placeholder, placeholder_fg, self.cget("fg") + self.putp() + self.bind("", self.toggle) + self.bind("", self.toggle) + + def putp(self): + self.delete('1.0', tk.END) + self.insert('1.0', self.p) + self.config(fg=self.p_fg) + self.p_a = True + + def toggle(self, event): + if self.p_a: + self.delete('1.0', tk.END) + self.config(fg=self.fg) + self.p_a = False + elif self.get('1.0', tk.END).replace(' ', '').replace('\\n', '') == '': self.putp() + + def get(self, i1='1.0', i2=tk.END): return '' if self.p_a else super().get(i1, i2) + + def is_placeholder(self, b): + self.p_a = b + self.config(fg=self.p_fg if b == True else self.fg) + + def get_placeholder(self): return self.p +''' + + for item in data[0]: + if item['type'] in ['textbox', 'textarea'] and 'placeholder' in item: + counts[item['type']] += 1 + template += elements[item['type']](item, counts[item['type']], True) + elif item['type'] == 'label': + counts[item['type']] += 1 + template += elements[item['type']](item, counts[item['type']], data[1][2]) + elif item['type'] in list(counts.keys()): + counts[item['type']] += 1 + template += elements[item['type']](item, counts[item['type']]) + else: + template += elements[item['type']](item) + + template += '\nwindow.resizable(False, False)\nwindow.mainloop()\n' + + if multiple: + write_file(template, out, data[1][4]) + else: + write_file(template, out) + + threads = [] + for data_item in parsed: + thread = threading.Thread(target=generate_gui, args=(data_item,)) + thread.start() + threads.append(thread) + + for thread in threads: + thread.join() + + return True diff --git a/tkforge.iss b/tkforge.iss new file mode 100644 index 0000000..13f38f2 --- /dev/null +++ b/tkforge.iss @@ -0,0 +1,68 @@ +#define Name "TkForge" +#define Version "2.1.0" +#define Author "Axorax" +#define URL "https://github.com/axorax/tkforge" +#define ExeName "TkForge.exe" + +[Setup] +AppId={{2817A8C8-9721-4DF0-A238-6F1A0B6E24B8} +Name={#Name} +AppVersion={#Version} +;AppVerName={#Name} {#Version} +AppPublisher={#Author} +AppPublisherURL={#URL} +AppSupportURL={#URL} +AppUpdatesURL={#URL} +DefaultDirName={autopf}\{#Name} +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +OutputBaseFilename=TkForge-setup +SetupIconFile=assets\icon.ico +Compression=lzma +SolidCompression=yes +WizardStyle=modern + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" +Name: "armenian"; MessagesFile: "compiler:Languages\Armenian.isl" +Name: "brazilianportuguese"; MessagesFile: "compiler:Languages\BrazilianPortuguese.isl" +Name: "bulgarian"; MessagesFile: "compiler:Languages\Bulgarian.isl" +Name: "catalan"; MessagesFile: "compiler:Languages\Catalan.isl" +Name: "corsican"; MessagesFile: "compiler:Languages\Corsican.isl" +Name: "czech"; MessagesFile: "compiler:Languages\Czech.isl" +Name: "danish"; MessagesFile: "compiler:Languages\Danish.isl" +Name: "dutch"; MessagesFile: "compiler:Languages\Dutch.isl" +Name: "finnish"; MessagesFile: "compiler:Languages\Finnish.isl" +Name: "french"; MessagesFile: "compiler:Languages\French.isl" +Name: "german"; MessagesFile: "compiler:Languages\German.isl" +Name: "hebrew"; MessagesFile: "compiler:Languages\Hebrew.isl" +Name: "hungarian"; MessagesFile: "compiler:Languages\Hungarian.isl" +Name: "icelandic"; MessagesFile: "compiler:Languages\Icelandic.isl" +Name: "italian"; MessagesFile: "compiler:Languages\Italian.isl" +Name: "japanese"; MessagesFile: "compiler:Languages\Japanese.isl" +Name: "korean"; MessagesFile: "compiler:Languages\Korean.isl" +Name: "norwegian"; MessagesFile: "compiler:Languages\Norwegian.isl" +Name: "polish"; MessagesFile: "compiler:Languages\Polish.isl" +Name: "portuguese"; MessagesFile: "compiler:Languages\Portuguese.isl" +Name: "russian"; MessagesFile: "compiler:Languages\Russian.isl" +Name: "slovak"; MessagesFile: "compiler:Languages\Slovak.isl" +Name: "slovenian"; MessagesFile: "compiler:Languages\Slovenian.isl" +Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl" +Name: "turkish"; MessagesFile: "compiler:Languages\Turkish.isl" +Name: "ukrainian"; MessagesFile: "compiler:Languages\Ukrainian.isl" + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked + +[Files] +Source: "dist\{#ExeName}"; DestDir: "{app}"; Flags: ignoreversion + +[Icons] +Name: "{autoprograms}\{#Name}"; Filename: "{app}\{#ExeName}" +Name: "{autodesktop}\{#Name}"; Filename: "{app}\{#ExeName}"; Tasks: desktopicon + +[Run] +Filename: "{app}\{#ExeName}"; Description: "{cm:LaunchProgram,{#StringChange(Name, '&', '&&')}}"; Flags: nowait postinstall skipifsilent + diff --git a/tkforge.py b/tkforge.py new file mode 100644 index 0000000..da07c06 --- /dev/null +++ b/tkforge.py @@ -0,0 +1,53 @@ +import os +import argparse +from tk import tk_code +from colorama import Fore, init +from utils import extract_figma_id, check_for_updates + +init(autoreset=True) + +try: + exec(check_for_updates(False)) +except: + print("No updates!") + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Drag & drop in Figma to create a Python GUI with ease! Donate: " + Fore.BLUE + "https://patreon.com/axorax" + Fore.RESET) + + parser.add_argument('--id', type=str, help="Figma file ID or URL") + parser.add_argument('--token', type=str, help="Figma token") + parser.add_argument('--out', type=str, help="Output file path") + + parser.add_argument('args', nargs='*', help="id token output-path") + + args = parser.parse_args() + + if not any([args.id, args.token]) and args.args: + if len(args.args) == 2: + args.id, args.token = args.args + args.out = None + elif len(args.args) == 3: + args.id, args.token, args.out = args.args + + if args.out == '.': + args.out = os.getcwd() + + return args.id, args.token, args.out + +def main(): + file_id, token, output = parse_arguments() + + if not file_id or not token: + print(Fore.RED + "Provide both arguments id and token. Make sure to wrap URL in quotes(\").") + return + + print(Fore.YELLOW + "Processing...") + code = tk_code(extract_figma_id(file_id), token, output) + + if code == None: + print(Fore.RED + "The file ID, token or output path that you provided is invalid!") + else: + print(Fore.GREEN + "Success! Your code has been generated!") + +if __name__ == "__main__": + main() diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..8c183ee --- /dev/null +++ b/utils.py @@ -0,0 +1,68 @@ +import os +import requests +from urllib.parse import urlparse + +VERSION = "2.1.0" +BASE_URL = "https://raw.githubusercontent.com/Axorax/tkforge/refs/heads/main/" + +def check_for_updates(gui_info = True): + try: + global VERSION + response = requests.get(f"{BASE_URL}VERSION.txt") + response.raise_for_status() + online_version = response.text.strip() + 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 + else: + return "" + except requests.RequestException as e: + return "" + +def rgb_to_hex(r, g, b): + return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}" + +def get_foreground_color(r, g, b): + def linearize(c): + c /= 255 + return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 + + luminance = 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b) + return '#000000' if luminance > 0.179 else '#ffffff' + +def write_file(text, out=None, frame=None): + if out is None: + folder_path = 'TkForge' + else: + folder_path = os.path.join(out, 'TkForge') + + if not os.path.exists(folder_path): + os.makedirs(folder_path) + + if frame is not None: + file_name = f'frame_{frame}.py' + else: + file_name = 'main.py' + + with open(os.path.join(folder_path, file_name), 'w', encoding='utf-8') as file: + file.write(text) + +def extract_figma_id(url): + if url.startswith('http'): + url = urlparse(url) + + if 'figma.com' in url.netloc and ('/file/' in url.path or '/design/' in url.path): + path_parts = url.path.split('/') + if 'file' in path_parts: + file_index = path_parts.index('file') + elif 'design' in path_parts: + file_index = path_parts.index('design') + else: + return None + + if file_index + 1 < len(path_parts): + return path_parts[file_index + 1] + return url