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
+ +Drag & drop in Figma to create a Python GUI with ease
+ +Upvote on Product Hunt • Donate
+ + + +📺 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 Patreon — Check 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
+ +在 Figma 中拖放,轻松创建 Python 图形用户界面
+ + + + + +📺 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 步:点击 "确定"、"确定 "和 "确定",然后就完成了! + +--- + + \ 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