├── Files
├── installer-windows
│ └── CTkEasyEditor-1.45-win64.msi
└── zip-windows
│ └── CTkEasyEditor.zip
├── LICENSE
├── README.md
├── documentation
├── devlog.md
├── docs.md
└── install.md
├── screenshots
├── Master Update.png
├── image.png
├── snappingupdate.png
├── ss1.png
└── usage1.png
└── scripts
├── CTkError.py
├── CTkFileSelector.py
├── CTkImage.py
├── activewidgethandler.py
├── assets
├── icon.ico
└── icon.png
├── boilerplate.py
├── main.py
├── preferenceshandler.py
├── requirements.txt
└── settingseditor.py
/Files/installer-windows/CTkEasyEditor-1.45-win64.msi:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/Files/installer-windows/CTkEasyEditor-1.45-win64.msi
--------------------------------------------------------------------------------
/Files/zip-windows/CTkEasyEditor.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/Files/zip-windows/CTkEasyEditor.zip
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CTKEasyEditor
2 |
3 | An easy GUI editor for CustomTkinter in Python - think of it as a boilerplate generation tool for your CustomTkinter projects. Simply arrange elements, change their properties, and then export to a .py file ready to code in!
4 |
5 | Thanks to Tom Schimansky for their CustomTkinter development. Find the original page for CustomTkinter here: https://customtkinter.tomschimansky.com/
6 | The original documentation on CustomTkinter is excellent, and I recommend it for anyone starting off and struggling with the usage of this tool.
7 | Also thanks to Akascapes for providing the CTkColorMenu widget and CTkMenuBar widget.
8 |
9 | Note this is still a work in progress:
10 |
11 | 
12 |
13 | Zip and Installer should be the most recent stable release, the python scripts are the most recent experimental releases.
14 |
15 | Files, Windows Only (I can't figure out how to freeze to mac format). Just click on links and then press download:
16 |
17 | - [Download Installer](https://github.com/coding-beagle/CTKEasyEditor/blob/main/Files/installer-windows/CTkEasyEditor-1.4-win64.msi)
18 |
19 | - [Download As Zip](https://github.com/coding-beagle/CTKEasyEditor/blob/main/Files/zip-windows/CTkEasyEditor.zip)
20 |
21 | Other platforms must download and run python code yourself (I can't figure out cx_freeze):
22 |
23 | [Advanced Install Instructions](documentation\install.md)
24 |
25 | ![alt text]()
26 |
27 | This tool is still in development, please report any bugs or issues under the issues tab.
28 | Right now it seems to work okay, and the current implementation includes:
29 |
30 | - **Latest Update**:
31 | - Fixed a bug with the widgets' masters being exported incorrectly if the parent was the root element.
32 | - Added the ability to change widgets' parents on the fly.
33 | - Improved snapping capabilities even further
34 | - Made window dynamically resizable.
35 |
36 | - Easy Application Window Settings Management
37 | - Easy Active Widgets manager
38 | - Dragging and snapping of widgets
39 | - Widget Editing
40 | - Use of Built In Themes for CTK
41 | - Export to OOP and Procedural files
42 | - Preference Handler (i.e. names of modules, root element, etc)
43 | - Saving and opening of projects
44 | - Change widgets' parents on the fly!
45 |
46 | To be implemented soon:
47 |
48 | - Custom Theme Support
49 | - Some widgets don't play nice currently, namely CTkScrollableFrame, CTkTreeView and CTkSegmentedButton. I'll add these when I can get them to a stable version and playing nice.
50 |
51 | Hotkeys & Shortcuts:
52 |
53 | - CTRL --> Hold while dragging to prevent widget from snapping into place
54 | - Shift --> Enforce Snapping on Grid / Center lines only
55 | - ALT --> Only snap widget to other widgets, not the app center lines
56 | - Double Click --> Opens editor window on that widget
57 | - Right Click --> Opens context menu on widget (edit, duplicate, delete)
58 |
59 | - The standard save, save as and open hotkeys, i.e. ctrl+s, ctrl+shift+s, ctrl+o, etc
60 | - Control G --> Open the grid aligner
61 | - Control + arrow keys --> Adjust the grid size
62 | - Control R --> Toggle Window Size Adjustability
63 |
64 |
--------------------------------------------------------------------------------
/documentation/devlog.md:
--------------------------------------------------------------------------------
1 | **19-03-2024**
2 |
3 | Todo:
4 |
5 | - Frames not snapping properly?
6 |
7 | **11-03-2024**
8 |
9 | Todo:
10 |
11 | - Errors get thrown if widget is below master in active_widgets
12 | - I.e. Button gets created first, then frame. When button master is set to frame, we delete everything, and then redraw a new. Button gets created before frame is drawn, which gives error.
13 | - Similarly, when master widget is deleted, children widgets are not deleted from active_widgets
14 |
15 | Completed:
16 |
17 | - Added window resizing functionality
18 | - Refactored CTkError to display in middle of screen
19 | - Made good headway into resolving issues with widget height reordering
20 |
21 | **01-03-2024**
22 |
23 | **06-03-2024**
24 |
25 | Todo:
26 |
27 | - Errors get thrown if widget is below master in active_widgets
28 | - I.e. Button gets created first, then frame. When button master is set to frame, we delete everything, and then redraw a new. Button gets created before frame is drawn, which gives error.
29 | - Similarly, when master widget is deleted, children widgets are not deleted from active_widgets
30 |
31 | Completed:
32 |
33 | - Added basic functionality for master switching
34 |
35 | **01-03-2024**
36 |
37 | Todo:
38 |
39 | - Fix widgets editing others
40 |
41 | Completed:
42 | - Fixed duplicate widget editing
43 |
44 | **03-02-2024**
45 | Todo:
46 |
47 | -Complete documentation
48 |
49 | Bugs:
50 |
51 | - **(Fixed)** files saving as "None" when no path was selected
52 |
53 | Completed:
54 | - Added all new widget properties
55 | - Changed widget properties window placement
56 |
57 | **02-02-2024**
58 | Todo:
59 | - Add all of the new properties to widgets
60 |
61 | Completed:
62 | - Refactored settingseditor.py
63 |
64 | **30-01-2024**
65 | Todo:
66 |
67 | - Refactor settingseditor.py to have more granular control over widget properties
68 | - Might need to add custom theme support tomorrow
69 |
70 | Bugs:
71 |
72 | - **(Fixed)** First widget was not being loaded on new file
73 |
74 | Completed:
75 |
76 | - Refactored how widgets handle images
77 | - Subsequently fixed shifting layer of images
78 | - Reworked saving and opening file logic, now generates text first and if errors occur we don't write the file.
79 | - Frozen file and added to .exe
80 |
81 | **29-01-2024**
82 |
83 | Completed:
84 |
85 | - Active Widget Handler optimised
86 |
87 | **28-01-2024**
88 |
89 | Todo:
90 |
91 | - Add custom theme support
92 | - Active Widget Handler needs some optimisations
93 |
94 | Bugs encountered:
95 |
96 | - **(Fixed)** Lots of error messages but the app still seems to work fine
97 | - **(Fixed)** The error messages were because the app was not working fine.
98 | - **(Fixed)** Error messages were being caused by app window being duplicated in create_app_window() function
99 | - Icon not working now
100 |
101 | Completed:
102 |
103 | - Fixed editor window of elements opening a new window when clicked
104 | - Changed the widget IDs to be based on the numer of those elements, instead of number of total elements
105 | - 'Apply Settings' now correctly reloads all of the widgets when the app window is closed (wasn't working before)
106 | - boilerplate.py indenting issues for image objects
107 | - Added basic theme management
108 | - Added element rearranging (this is currently backwards compared to photoshop or other standard, in theory widgets should have higher draw priority the more they are on top)
109 | - Added project saving
110 |
111 | **27-01-2024**
112 |
113 | Todo:
114 |
115 | - Add user friendliness features, i.e. being able to rearrange element hierarchy
116 | - Theme editor / theme selector implementation
117 | - r/therewasanattempt to try and add line drawings to show snap
118 |
119 | Bugs encountered:
120 |
121 | - **(FIXED)** Duplicate on widgets with images, 'image_path', 'image_size_x', 'image_size_y' are being unpacked
122 | - **(FIXED)** Duplicate on widgets with different font sizes causes other properties to not be inherited (likely as a result of the font size handling in settingseditor.py)
123 |
124 | Completed:
125 |
126 | - Added preference window with dynamic element adjusting
127 | - OOP export implemented
128 | - Added snapping to other widgets (needs to be fine tuned)
129 |
130 | **26-01-2024**
131 |
132 | Big progress day, uni exams are done
133 |
134 | Todo:
135 |
136 | - Continue adding the editing menus for each widget (the specific ones are annoying)
137 | - Add Edit -> Preferences
138 | - - Preferences should contain things like export type (OOP mode or Procedural, etc),
139 | - - Also things like what is the ctk library called
140 | - Add Editor saving system, i.e. File -> save, File -> open etc, (unsure of implementation)
141 | - Active widget hierarchy adjustments (one fears the thought of touching activewidgethandler.py)
142 | - Theme editor implementation
143 |
144 | Bugs encountered:
145 |
146 | - **(FIXED)** Need to reopen window with all drawn elemnts when it is closed
147 | - Not a bug, but figure out a way to only import PIL libraries if it is needed, e.g. if there is an image object or something
148 |
149 | Completed:
150 |
151 | - Added dynamic system for adding widget editing
152 | - Completed a few of the important widgets
153 | - Added export to .py (only for procedural)
154 |
155 | **25-01-2024**
156 |
157 | Todo:
158 |
159 | - God please fix the code why is it so messy and bad and ill have to go through and reformat it again why did i choose python devleopemneinodjkosjopisdojiiogio;sg
160 | - Segmented button doesn't have drag functionality implemented (not in creation list for now)
161 | - TabView not implemented yet either
162 | - Finish widget editing functionality
163 | - Add logic to do naming (i.e. click on widget in active widgets and then rename that)
164 | - Add logic to move around active widgets in active tab (more drag and drop????)
165 |
166 | Bugs encountered:
167 |
168 | - Scrollable Frame doesn't delete properly
169 |
170 | Completed:
171 |
172 | - Fixed widget handler
173 | - Added a simple file selector widget
174 | - Added widget creation functionality
175 | - Added export to .py for basic root boilerplate
176 | - Started with widget editing functionality
177 |
178 | **24-01-2024**
179 |
180 | Todo:
181 |
182 | - Fix Widget Handler
183 |
184 | Bugs encountered:
185 |
186 | - **(FIXED)** Right click menu not completed functionality
187 | - **(FIXED)** Need to add widget adding functionality
188 | - **(FIXED)** Improve Widget Handler
189 |
190 | Completed:
191 |
192 | - Dragging elements
193 | - Right Click Menu Implemented
194 |
195 | **23-01-2024**
196 |
197 | Todo:
198 |
199 | - Fix dragging elements (probably need to refactor the mouse moving code)
200 |
201 | Bugs encountered:
202 |
203 | - **(FIXED)** Fix lag on clicking top bar
204 |
205 | Completed:
206 |
207 | - Added basic functionality
208 |
--------------------------------------------------------------------------------
/documentation/docs.md:
--------------------------------------------------------------------------------
1 | # This is going to sound like the ramblings of a mad man. That's what python does to someone.
2 |
3 | ## main.py
4 |
5 | Responsibilities:
6 |
7 | - Bring together every element of the app.
8 | - Generate Widgets and Call Utility functions, i.e. open widget property editor
9 | - Handle Saving and Loading of projects
10 |
11 | How it accomplishes this
12 |
13 | **Editor Window**:
14 |
15 | - editor_window is the root element
16 | - The window settings get drawn in the first iteration when running the app.
17 | - We populate it with all of the different widgets for editing, i.e. all of the entry for window setting, the menubar, the menubar callbacks
18 |
19 | **App window**:
20 |
21 | - The App preview window is a ctk.CTkTopLevel widget with master being editor_window. It is created on app start up, and whenever 'apply settings' is pressed.
22 | - When 'apply settings' is pressed, we check to see if an app element exists, as the toplevel is stored in the global variable 'app'. If it does not, then we create a new instance of 'app' using the create_app_window() function.
23 | - create_app_window() returns a ctk.CTkTopLevel widget based on the parameters present in frame_window_settings. These values are defaulted to (500, 500, title="", icopath = "") the app window always appears to the right of the editor.
24 | - we then call draw_widgets() to populate the app with widgets (if they exist)
25 |
26 | **Widget handling**:
27 |
28 | - Widgets are as stored as a dictionary, as part of a global list titled "**active_widgets**". This stores the fields:
29 | - "widget" = the actual instance of the ctk widget
30 | - "location" = a tuple with the x,y coordinates of the widget relative to the app position
31 | - "wiget_name" = a string of what is used to display in the create widget options (explained later)
32 | - "widget_type" = a string reference of the ctk widget type, i.e. !ctk.ctkbutton
33 | - "kwargs" = a dictionary of key value pairs used to generate the boilerplate code and also update attributes of each widget
34 | - "widget_id" = a string of what the widget is called in the generated code. can be changed by the user
35 | - "has bindings" = a bool of whether or not the widget instance has bindings, such as right click bindings, drag bindings, etc
36 | - "image_path" = a string of the path to the image used for the widget (empty if unused)
37 | - "image_size" = a tuple of the dimensions of the image
38 | - "image" = the ctk.Image object
39 |
40 | - **widget_class** is a dictionary that maps readable names to the equivalent ctk reference.
41 | - e.g. Button gets mapped to "ctk.CTkButton"
42 | - needed because the option menu to add widgets, (**optionmenu_add_widget**) gets the callback command of create_widget
43 |
44 | - **create_widget()** takes this readable name, as well as optional parameters to be explained later, in order to instatiate an instance of the equivalent ctk type. This is because the option menu (the drop down widget used to add widgets) calls its command= callback with the argument of the option that is selected.
45 | - e.g. create_widget("Button") is called when the user selects button from the drop down list.
46 | - this is how we infer to create the correct type, using the widget_class dict.
47 | - create_widget() then adds an instance of this widget to the middle of the screen and populates the rest of the dictionary with relevant information.
48 | - create_widget() optionally takes the parameters of bool duplicate, widget_to_duplicate and kwarg_list, all of which are used to create duplicates of existing elements
49 | - When we duplicate widgets, we create a widget of the same type as the widget to be duplicated (which is why we store widget_name, so we can pass in widget.get("widget_name")). This can be improved in the future.
50 | - the created_widget is then added to the list of global active_widgets, where add_bindings() is then called.
51 |
52 | - add_bindings()
53 |
54 | // todo unfinished
--------------------------------------------------------------------------------
/documentation/install.md:
--------------------------------------------------------------------------------
1 | **To install and run script (assuming you have git and pip):**
2 |
3 | ```
4 | $ git clone https://github.com/coding-beagle/ctkeasyeditor.git
5 | ```
6 |
7 | Navigate to scripts, e.g.
8 |
9 | ```
10 | $ cd ctkeasyeditor
11 | ```
12 |
13 | Recommended: start a new python virtual environment in the scripts directory:
14 | Depending on your IDE (i.e. vscode) you might need to set the venv manually
15 |
16 | ```
17 | $ cd scripts
18 | $ python -m venv venv
19 | $ venv/scripts/activate.ps1
20 | ```
21 |
22 | Install the required packages:
23 |
24 | ```
25 | $ pip install -r requirements.txt
26 | ```
27 |
28 | Finally run main.py
29 |
30 | ```
31 | $ python main.py
32 | ```
33 |
--------------------------------------------------------------------------------
/screenshots/Master Update.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/screenshots/Master Update.png
--------------------------------------------------------------------------------
/screenshots/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/screenshots/image.png
--------------------------------------------------------------------------------
/screenshots/snappingupdate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/screenshots/snappingupdate.png
--------------------------------------------------------------------------------
/screenshots/ss1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/screenshots/ss1.png
--------------------------------------------------------------------------------
/screenshots/usage1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/screenshots/usage1.png
--------------------------------------------------------------------------------
/scripts/CTkError.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 |
3 | class CTkError(ctk.CTkFrame):
4 | def __init__(self, *args, title="Error",size_x=140, size_y=90,error_message, button_1_text, button_2_text="", **kwargs):
5 | super().__init__(*args)
6 | ## Geometry and Theme Settings
7 |
8 | self.top_level = ctk.CTkToplevel(self)
9 | self.top_level.focus_set()
10 |
11 | print(self.winfo_screenwidth()/2 - self.winfo_width())
12 | print(self.winfo_screenheight()/2 - self.winfo_height())
13 |
14 | self.top_level.geometry(f"{size_x}x{size_y}+{int(self.winfo_screenwidth()/2 - self.winfo_width())}+{int(self.winfo_screenheight()/2 - self.winfo_height())}")
15 | self.top_level.title(title)
16 | self.top_level.resizable(False, False)
17 |
18 | self.columnconfigure((0,2), weight=1)
19 | self.rowconfigure((0,2), weight=1)
20 |
21 | self.Label_1 = ctk.CTkLabel(self.top_level,width=100,text=error_message,wraplength=size_x-50, justify='center')
22 | self.Label_1.grid(row=0,column=1, padx=30,pady=10)
23 |
24 | if(button_1_text and not button_2_text):
25 | self.Button_0 = ctk.CTkButton(self.top_level,corner_radius=20, width=100,text=button_1_text, command=lambda: self.destroy())
26 | self.Button_0.grid(row=1, column=1,pady=(0,10))
27 |
28 | if(button_2_text):
29 | self.Button_0 = ctk.CTkButton(self.top_level,corner_radius=20, width=100,text=button_1_text, command=lambda: self.destroy())
30 | self.Button_0.grid(row=1, column=0,pady=(0,20))
31 |
32 | self.Button_0 = ctk.CTkButton(self.top_level,corner_radius=20,text=button_2_text, command=lambda: self.destroy())
33 | self.Button_0.grid(row=1, column=2)
34 |
35 | self.top_level.attributes('-topmost', True)
--------------------------------------------------------------------------------
/scripts/CTkFileSelector.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 | from tkinter import filedialog
3 | import os
4 |
5 | class CTkFileSelector(ctk.CTkFrame):
6 | def __init__(self, *args, label, select_button_width=10, select_button_height=25, entry_width=50, entry_height=30, entry_text="file/path", entry_padding, **kwargs):
7 | super().__init__(*args, *kwargs)
8 | self.configure(fg_color="transparent")
9 | self.entry_file_path = ctk.CTkEntry(self, placeholder_text=entry_text, height=entry_height, width=entry_width)
10 | self.entry_file_path.grid(column=1, row=0,padx=entry_padding)
11 | self.label_entry_name = ctk.CTkLabel(self, text=label)
12 | self.label_entry_name.grid(column=0, row=0, sticky='w')
13 | self.button_select_icon = ctk.CTkButton(self, text="...", width=select_button_width, height=select_button_height, command=self.set_path)
14 | self.button_select_icon.grid(column=2, row=0)
15 |
16 | def set_path(self):
17 | self.currdir = os.getcwd()
18 | self.path = filedialog.askopenfile(initialdir=self.currdir)
19 | if(self.path is not None):
20 | self.entry_file_path.delete(0, "end")
21 | self.entry_file_path.insert(0, str(self.path.name))
22 |
23 | def get_path(self):
24 | return self.entry_file_path.get()
25 |
26 | def get_entry_element(self):
27 | return self.entry_file_path
--------------------------------------------------------------------------------
/scripts/CTkImage.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 |
3 | class CTkImageFrame(ctk.CTkLabel):
4 | def __init__(self, *args, **kwargs):
5 | super().__init__(*args, **kwargs)
6 |
7 | self.configure(text="")
--------------------------------------------------------------------------------
/scripts/activewidgethandler.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 | import tkinter as tk
3 | from icecream import ic
4 | from CTkError import CTkError
5 |
6 | class WidgetName(ctk.CTkFrame):
7 | def __init__(self, *args,
8 | width: int = 200,
9 | height: int = 40,
10 | widget,
11 | edit_button_cb,
12 | delete_button_cb,
13 | name_change_cb,
14 | move_up_cb,
15 | move_down_cb,
16 | change_master_cb,
17 | **kwargs):
18 | super().__init__(*args, width=width, height=height, **kwargs)
19 |
20 | self.columnconfigure(0, weight=5) # Label column
21 | self.columnconfigure(1, weight=5)
22 | self.columnconfigure(2, weight=1) # Expanding middle column
23 | self.columnconfigure(3, weight=0) # Edit button column
24 | self.columnconfigure(4, weight=0) # Delete button column
25 |
26 | self.masters = None
27 | self.change_master = change_master_cb
28 |
29 | self.widget_ref = widget
30 |
31 | self.mouse_left = False
32 |
33 | self.change_name = name_change_cb
34 |
35 | self.move_up = move_up_cb
36 | self.move_down = move_down_cb
37 |
38 | self.entry = ctk.CTkEntry(self, width=120)
39 | self.text = tk.StringVar(self.entry, self.widget_ref.get("widget_id"))
40 | self.old_name = self.widget_ref.get("widget_id")
41 |
42 | self.entry.configure(textvariable=self.text)
43 | self.entry.configure(state="disabled")
44 | self.entry.grid(column=0, row=0, sticky='w', columnspan=1, padx=5, rowspan=2)
45 | self.entry.bind('', self.edit_text)
46 | self.entry.bind('', self.stop_edit_text)
47 | self.entry.bind('', self.stop_edit_text)
48 |
49 | self.edit_button = ctk.CTkButton(self, font=('roboto', -20),text="⛭", command=edit_button_cb, width=40, height=40)
50 | self.edit_button.grid(column=3, row=0, padx=2,pady=2, sticky='e', rowspan=2)
51 |
52 | self.remove_button = ctk.CTkButton(self, font=(('roboto', -25)), text="×", command=delete_button_cb, width=40, height=40)
53 | self.remove_button.grid(column=4, row=0, padx=2,pady=2, sticky='e', rowspan=2)
54 |
55 | self.optionmenu_masters = ctk.CTkOptionMenu(self, font=('roboto', -12), command=lambda e: self.switch_master(e), width=135, height=40, values=["root"],dynamic_resizing=False)
56 | self.optionmenu_masters.grid(column=1, row=0, padx=3, sticky='e', rowspan=2)
57 |
58 | self.up_button = ctk.CTkButton(self, font=('roboto', -10), text='⮝', width=20,height=10, command=self.move_up)
59 | self.up_button.grid(column=2, row=0, sticky='ne', pady=(2,0), padx=(0,1))
60 |
61 | self.down_button = ctk.CTkButton(self, font=('roboto', -10), text='⮟', width=20,height=10, command=self.move_down)
62 | self.down_button.grid(column=2, row=1, sticky='se', pady=(0,2), padx=(0,1))
63 |
64 | def switch_master(self, master):
65 | try:
66 | master_ref = [i for i in self.masters if i['Name'] == master][0]
67 | self.change_master(self.widget_ref, master_ref)
68 | self.optionmenu_masters.set(master)
69 | except TypeError:
70 | self.update_masters()
71 | self.optionmenu_masters.set(self.masters[0]['Name'])
72 |
73 | def edit_text(self, event):
74 | self.entry.configure(state="normal")
75 | self.old_name = self.entry.get()
76 |
77 | def mouse_enter(self, event):
78 | self.mouse_is_on = True
79 |
80 | def mouse_left(self, event):
81 | self.mouse_is_on = False
82 |
83 | def stop_edit_text(self, event):
84 | try:
85 | self.change_name(self.widget_ref, self.entry.get())
86 | except NameError: ## add toplevel error here
87 | self.entry.delete(0, tk.END)
88 | self.entry.insert(0, self.old_name)
89 |
90 | CTkError(self.master, button_1_text="Okay", error_message="Widgets cannot have the same name!",size_x=150, size_y=120)
91 |
92 | self.entry.configure(state="disabled")
93 |
94 | def get_widget(self):
95 | return self.widget_ref
96 |
97 | def update_masters(self):
98 | self.optionmenu_masters.configure(values=[i['Name'] for i in self.masters])
99 | try:
100 | master = [j['Name'] for j in self.masters if self.widget_ref['master'] == j['Name']][0]
101 | self.optionmenu_masters.set(master)
102 | except:
103 | pass
104 |
105 |
106 | class WidgetHandler(ctk.CTkScrollableFrame):
107 | def __init__(self, *args, **kwargs):
108 | super().__init__(*args, **kwargs)
109 |
110 | self.scrollFrame = ctk.CTkScrollableFrame(self, height=kwargs.get("height"),width=kwargs.get("width"))
111 | self.active_widgets = []
112 | self.active_row_widgets = []
113 | self.columnconfigure(0, weight=10)
114 |
115 | def add_widget(self, widget, edit_cb, delete_cb, name_change_cb, move_up_cb, move_down_cb, masters_list, change_master_command):
116 | self.widget_data_dict = {"widget": widget, "edit_cb": edit_cb, "delete_cb": delete_cb, "name_change_cb": name_change_cb, "move_up": move_up_cb, "move_down": move_down_cb}
117 | self.active_widgets.append(self.widget_data_dict)
118 | new_widget = WidgetName(self, height=30,width=300,widget=widget, edit_button_cb=edit_cb, delete_button_cb=delete_cb, name_change_cb=name_change_cb, move_up_cb=move_up_cb,move_down_cb=move_down_cb, change_master_cb=change_master_command)
119 | self.active_row_widgets.append(new_widget)
120 | new_widget.grid(row=len(self.active_widgets), sticky='ew')
121 | self.update_masters_list(masters_list)
122 |
123 | def update_masters_list(self, list):
124 | for widget in self.active_row_widgets:
125 | widget.masters = list
126 | widget.update_masters()
127 |
128 | # def update_grid(self): # redraws the entire grid
129 | # self.active_row_widgets = []
130 | # self.clear_grid()
131 | # for index,widget in enumerate(self.active_widgets):
132 | # self.name = WidgetName(self, height=30,width=300,widget=widget.get("widget"), edit_button_cb=widget.get('edit_cb'), delete_button_cb=widget.get('delete_cb'), name_change_cb=widget.get("name_change_cb"), move_up_cb=widget.get("move_up"),move_down_cb=widget.get("move_down"))
133 | # self.name.grid(row=index, sticky='ew')
134 | # self.active_row_widgets.append((self.name))
135 |
136 | def clear_grid(self):
137 | for widget in self.active_row_widgets:
138 | widget.destroy()
139 | self.active_row_widgets = []
140 | self.active_widgets = []
141 |
142 | def remove_widget(self, widget):
143 | for index, row_widget in enumerate(self.active_row_widgets):
144 | if(row_widget.get_widget()["widget"] == widget):
145 | self.active_row_widgets[index].destroy()
146 | self.active_row_widgets.pop(index)
147 | return
148 |
149 | def swap_widget_from_to(self, from_index, to_index):
150 | self.active_row_widgets[from_index].grid(row=to_index, sticky='ew')
151 | self.active_row_widgets[to_index].grid(row=from_index, sticky='ew')
152 | self.active_row_widgets[from_index], self.active_row_widgets[to_index] = self.active_row_widgets[to_index], self.active_row_widgets[from_index]
153 |
154 |
155 | def check_widget(self, widget):
156 | output = False
157 | for active_widgets in self.active_widgets:
158 | if widget == active_widgets.get('widget').get('widget'): # todo fiX
159 | return True
160 | return output
161 |
--------------------------------------------------------------------------------
/scripts/assets/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/scripts/assets/icon.ico
--------------------------------------------------------------------------------
/scripts/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/scripts/assets/icon.png
--------------------------------------------------------------------------------
/scripts/boilerplate.py:
--------------------------------------------------------------------------------
1 | import shutil
2 | import os
3 | from icecream import ic
4 |
5 | class BoilerPlateHandler():
6 | def __init__(self):
7 | self.preferences = {}
8 | self.ctk_module = ""
9 | self.tk_module = ""
10 | self.need_images = False
11 | self.need_commands = False
12 |
13 | def set_preferences(self, dict):
14 | self.preferences = dict
15 | self.ctk_module = self.preferences.get('CustomTkinter Module Name:')['value']
16 | self.tk_module = self.preferences.get('Tkinter Module Name:')['value']
17 | self.root = self.preferences.get('Root Name:')['value']
18 | self.export_oop = self.preferences.get("Export as OOP?")['value']
19 | self.classname = self.preferences.get("Class Name (OOP Only):")['value']
20 |
21 | if(self.export_oop and self.classname == ""):
22 | self.classname = f"{self.root[:-1].upper()}{self.root[:1]}"
23 |
24 | def check_for_images(self, active_widgets_list, icon_path): # this flag determines whether or not we need to include the PIL Image libraries
25 | if(icon_path):
26 | self.need_images = True
27 | return
28 | for active_widget in active_widgets_list:
29 | if("image_path" in active_widget):
30 | self.need_images = True
31 | return
32 | else:
33 | self.need_images = False
34 |
35 | def check_for_commands(self, active_widgets_list): # this flag determines whether or not we need to write out the functions for the command of buttons
36 | for active_widget in active_widgets_list:
37 | try:
38 | if('command_name' in active_widget):
39 | self.need_commands = True
40 | return
41 | except KeyError:
42 | pass
43 | self.need_commands = False
44 | return
45 |
46 | def write_callbacks(self, active_widgets_list):
47 | text = ''
48 | if(self.need_commands):
49 | for active_widget in active_widgets_list:
50 | if("command_name" in active_widget and active_widget["command_name"] is not None):
51 | command_to_write = active_widget.get("command_name")
52 | command_to_write = command_to_write.replace(" ", "_")
53 | else:
54 | command_to_write = None
55 |
56 | if(command_to_write is not None and text.find(str(command_to_write)) == -1): # check if widget has a command= property associated to it, or if the command callback already exists
57 | text += f"""{' ' if self.export_oop else ''}def {command_to_write} ({'self' if self.export_oop else ''}):
58 | {' ' if self.export_oop else ' '} ## callback code goes here
59 | {' ' if self.export_oop else ' '}return\n"""
60 |
61 | return text
62 |
63 | def imports(self):
64 | text = f"import customtkinter as {self.ctk_module}\n"
65 | if(self.need_images):
66 | text += f"from PIL import ImageTk, Image\n"
67 | text += f"import tkinter as {self.tk_module}\n"
68 | return text
69 |
70 | def basic_app_window(self,size_x, size_y, icon_path, output_src, title="app", theme='blue', active_widgets_list=[]):
71 | if(title == ''): title = self.root
72 | callbacks = self.write_callbacks(active_widgets_list)
73 | self.callback_text = f"\n{callbacks}\n"
74 | if(self.export_oop):
75 | text = f"""
76 | class {self.classname}({self.ctk_module}.CTk): {self.callback_text if self.callback_text != "" else ''}
77 | def __init__(self):
78 | super().__init__()
79 | ## Geometry and Theme Settings
80 | {self.ctk_module}.set_appearance_mode("dark")
81 | {self.ctk_module}.set_default_color_theme("{theme}")
82 |
83 | self.geometry("{size_x}x{size_y}")
84 | self.title("{title}")"""
85 | if(icon_path):
86 | filename = icon_path.split("/")[-1]
87 | try:
88 | shutil.copyfile(icon_path, f"{output_src}/assets/{filename}")
89 | except FileNotFoundError:
90 | os.makedirs(f"{output_src}/assets")
91 | shutil.copyfile(icon_path, f"{output_src}/assets/{filename}")
92 | except shutil.SameFileError:
93 | pass # file exists in directory where we're trying to write to, so we don't care
94 | text += f"""
95 | ## Icon gets set here
96 | self.icon_path = ImageTk.PhotoImage(file="{output_src}/assets/{filename}")
97 | self.wm_iconbitmap()
98 | self.iconphoto(True, self.icon_path)"""
99 | return f"{text}\n"
100 | else:
101 | text =f"""
102 | {self.write_callbacks(active_widgets_list)}
103 |
104 | ## Geometry and Theme Settings
105 | {self.ctk_module}.set_appearance_mode("dark")
106 | {self.ctk_module}.set_default_color_theme("{theme}")
107 |
108 | {self.root} = {self.ctk_module}.CTk()
109 | {self.root}.geometry("{size_x}x{size_y}")
110 | {self.root}.title("{title}")"""
111 | if(icon_path):
112 | filename = icon_path.split("/")[-1]
113 | try:
114 | shutil.copyfile(icon_path, f"{output_src}/assets/{filename}")
115 | except FileNotFoundError:
116 | os.makedirs(f"{output_src}/assets")
117 | shutil.copyfile(icon_path, f"{output_src}/assets/{filename}")
118 | except shutil.SameFileError:
119 | pass # file exists in directory where we're trying to write to, so we don't care
120 | text += f"""
121 | ## Icon gets set here
122 | icon_path = ImageTk.PhotoImage(file="{output_src}/assets/{filename}")
123 | {self.root}.wm_iconbitmap()
124 | {self.root}.iconphoto(True, icon_path)"""
125 | return text + "\n"
126 |
127 |
128 | def widget_code(self, widget, output_src): # take in widget, create an instance of it using its name, configure all of its kwargs,
129 | text = ""
130 | kwargs = widget.get("kwargs")
131 |
132 | if(widget['master'] != self.root):
133 | arguments = widget['master'].replace(" ", "_")
134 | else:
135 | if(self.export_oop):
136 | arguments = "self"
137 | else:
138 | arguments = self.root
139 | self.image_exists = False
140 |
141 | widget_name = widget.get("widget_id")
142 | widget_name = widget_name.replace(" ", "_")
143 |
144 | if("image_path" in widget):
145 | self.image_exists = True
146 | arguments += f",image={'self.' if self.export_oop else ''}image_{widget_name}"
147 |
148 | for key, arg in kwargs.items():
149 | arguments += ","
150 | arguments += str(key)
151 | arguments += "="
152 | if isinstance(arg, str):
153 | arguments += f'"{arg}"' # Add quotation marks around the string
154 | else:
155 | arguments += str(arg)
156 |
157 | if(self.image_exists):
158 | image_path = widget["image_path"]
159 | filename = image_path.split("/")[-1]
160 | im_x, im_y = widget["image_size"]
161 | try:
162 | shutil.copyfile(image_path, f"{output_src}/assets/{filename}") # copy image file to new directory
163 | except FileNotFoundError: # assets folder doesn't exist, so we make one
164 | os.makedirs(f"{output_src}/assets")
165 | shutil.copyfile(image_path, f"{output_src}/assets/{filename}")
166 | except shutil.SameFileError:
167 | pass
168 | text += f"\n{' self.' if self.export_oop else ''}image_{widget_name} = {self.ctk_module}.CTkImage(dark_image=Image.open('{output_src}/assets/{filename}'), size=({im_x}, {im_y}))"
169 |
170 | if(self.export_oop):
171 | arguments = arguments.replace(f"{widget['master'].replace(' ', '_')}", f"self.{widget['master'].replace(' ', '_')}")
172 | if(arguments == f"self.{self.root}"):
173 | arguments="self"
174 |
175 |
176 | x,y = widget.get("location")
177 |
178 | widget_type = widget.get("widget_type").split(".")[-1][:-2]
179 | if(widget_type == 'CTkImageFrame'):
180 | widget_type = 'CTkLabel'
181 | arguments += ',text=""'
182 |
183 | if("command_name" in widget and widget["command_name"] is not None):
184 | widget_command = widget.get('command_name').replace(' ', '_')
185 | else:
186 | widget_command = None
187 |
188 | text += f"""
189 | {" self." if self.export_oop else ""}{widget_name} = {self.ctk_module}.{widget_type}({arguments}{f",command={'self.' if self.export_oop else ''}{widget_command}" if widget_command is not None else ""})
190 | {" self." if self.export_oop else ""}{widget_name}.place(x={int(x)}, y={int(y)})\n"""
191 | return text
192 |
193 | def main_loop(self):
194 | text = "\n"
195 | if(self.export_oop):
196 | text += f"{self.root} = {self.classname}()"
197 | text += f"\n{self.root}.mainloop()"
198 | return text
199 |
200 |
--------------------------------------------------------------------------------
/scripts/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import tkinter as tk
3 | from tkinter import filedialog
4 | from PIL import ImageTk, Image, ImageDraw
5 | import customtkinter as ctk
6 | from CTkMenuBar import *
7 | from icecream import ic
8 | import keyboard
9 | from activewidgethandler import *
10 | from boilerplate import *
11 | from settingseditor import *
12 | from CTkFileSelector import *
13 | from preferenceshandler import *
14 | from CTkImage import *
15 | from CTkError import *
16 | import json
17 | from sys import platform
18 | import math
19 |
20 | widget_types = {
21 | "Add Widgets Here": None,
22 | "Button": ctk.CTkButton,
23 | "Label": ctk.CTkLabel,
24 | "Image": CTkImageFrame,
25 | "Text Box": ctk.CTkTextbox,
26 | "Check Box": ctk.CTkCheckBox,
27 | "Combo Box": ctk.CTkComboBox,
28 | "Entry": ctk.CTkEntry,
29 | "Frame": ctk.CTkFrame,
30 | "Option Menu": ctk.CTkOptionMenu,
31 | "Progress Bar": ctk.CTkProgressBar,
32 | "Radio": ctk.CTkRadioButton,
33 | # "Scrollable Frame": ctk.CTkScrollableFrame, # Drag doesnt work for this
34 | "Scroll Bar": ctk.CTkScrollbar,
35 | # "Segment Button": ctk.CTkSegmentedButton, Drag is broken for this
36 | "Slider": ctk.CTkSlider,
37 | "Switch": ctk.CTkSwitch,
38 | # "Tab View": ctk.CTkTabview Drag is broken for this
39 | }
40 |
41 | def change_grid(tuple_up_down):
42 | if(tuple_up_down[0] and tuple_up_down[1]):
43 | if(export_preferences.get("Grid Count X:")["value"] > 1):
44 | export_preferences.get("Grid Count X:")["value"] -= 1
45 | elif(tuple_up_down[0] and not(tuple_up_down[1])):
46 | export_preferences.get("Grid Count X:")["value"] += 1
47 | elif(not(tuple_up_down[0]) and tuple_up_down[1]):
48 | if(export_preferences.get("Grid Count Y:")["value"] > 1):
49 | export_preferences.get("Grid Count Y:")["value"] -= 1
50 | elif(not(tuple_up_down[0]) and not(tuple_up_down[1])):
51 | export_preferences.get("Grid Count Y:")["value"] += 1
52 |
53 | toggle_grid()
54 | toggle_grid()
55 |
56 | def toggle_grid(*args):
57 | global dragging
58 | if(not(dragging)):
59 | global background
60 | export_preferences.get("Grid Edit Mode:")["value"] = not(export_preferences.get("Grid Edit Mode:")["value"])
61 | if(export_preferences.get("Grid Edit Mode:").get("value")):
62 | height = int(entry_height.get())
63 | width = int(entry_width.get())
64 | grid_spacing_x = width / (int(export_preferences.get("Grid Count X:")["value"]) + 1)
65 | grid_spacing_y = height / (int(export_preferences.get("Grid Count Y:")["value"]) + 1)
66 | im = Image.new(mode = "RGBA", size = (width, height), color=(0,0,0, 0))
67 | draw = ImageDraw.Draw(im)
68 | for x in (range(1, int(export_preferences.get("Grid Count X:")["value"])+ 1)):
69 | draw.line([(int((x)*grid_spacing_x),0),(int((x)*grid_spacing_x), height)], (0, 128,128,255), 1)
70 | for y in (range(1, int(export_preferences.get("Grid Count Y:")["value"])+1)):
71 | draw.line([(0,int((y)*grid_spacing_y)),(width, int((y)*grid_spacing_y))], (0, 128,128, 255), 1)
72 | image = ctk.CTkImage(dark_image=im, size=(width,height))
73 | background = ctk.CTkLabel(app, image=image, text='', height=height, width=width)
74 | background.place(x=0,y=0)
75 | draw_widgets(app, update_widgets=True, delete_existing_widgets=True)
76 | else:
77 | background.destroy()
78 |
79 | export_preferences = {
80 | "Grid Edit Mode:": {"value": False, "cb": toggle_grid},
81 | "Grid Count X:": {"value": 2, "cb": None},
82 | "Grid Count Y:": {"value": 2, "cb": None},
83 | "Snapping Sensitivity": {"value": 5, "cb": None},
84 | "Export as OOP?": {"value": True, "cb": None},
85 | "File Name:": {"value": "generated_file", "cb": None},
86 | "CustomTkinter Module Name:": {"value": "ctk", "cb": None},
87 | "Tkinter Module Name:": {"value": "tk", "cb": None},
88 | "Root Name:": {"value": "root", "cb": lambda: frame_widgets.update_masters_list(find_frames())},
89 | "Class Name (OOP Only):": {"value": "Root", "cb": None},
90 | }
91 |
92 | def find_widget_in_active_widgets(widget): # this takes in a CTk Widget Object and finds its corresponding entry in the active_widgets dictionary
93 | for active_widget in active_widgets:
94 | if active_widget.get("widget") == widget:
95 | return active_widget
96 |
97 | def set_theme_to_user_theme():
98 | theme = combo_theme_selector.get()
99 | theme = theme.replace(" ", "-")
100 | theme = theme.lower()
101 | ctk.set_default_color_theme(theme)
102 |
103 | # def kill_snap_widget(arg):
104 | # global label_snap_lines_horizontal, label_snap_lines_vertical
105 | # if(label_snap_lines_vertical):
106 | # label_snap_lines_horizontal.forget()
107 | # if(label_snap_lines_horizontal):
108 | # label_snap_lines_vertical.forget()
109 |
110 | def make_draggable(widget):
111 | widget.get("widget").bind("", on_drag_start)
112 | widget.get("widget").bind("", on_drag_motion)
113 | widget.get("widget").bind("", on_drag_end)
114 | # widget.get("widget").bind("", kill_snap_widget)
115 |
116 | def on_drag_end(event):
117 | global dragging
118 | dragging = False
119 |
120 | def on_drag_start(event):
121 | global dragging
122 | dragging = True
123 | widget = event.widget.master
124 | widget._drag_start_x = event.x
125 | widget._drag_start_y = event.y
126 |
127 | # as long as i hide this function in my terminal everything is okay
128 | # its responsibility is to return the x point of either the center line or a widget's center
129 | # if it's x position is different by 20 pixels, same with y
130 | # it achieves that through some black magic codde
131 | def check_other_widgets(widget_x_mid, widget_y_mid, widget, test_x, widget_half_x, widget_half_y):
132 | snapping_sensitivity = int(export_preferences["Snapping Sensitivity"]["value"])
133 | for active_widget in active_widgets:
134 | if(widget == active_widget.get("widget") or active_widget['widget'].master == widget or find_widget_in_active_widgets(widget)['master'] != active_widget['master']):
135 | # ic(active_widget['master'])
136 | continue
137 | else:
138 | active_widget_x_midpoint, active_widget_y_midpoint = active_widget.get("location")
139 | active_widget_width, active_widget_height = active_widget.get("widget").cget("width"), active_widget.get("widget").cget("height")
140 | active_widget_x_midpoint += active_widget.get("widget").winfo_width() / 2
141 | if(not keyboard.is_pressed("shift")):
142 | if(test_x):
143 | if(abs(widget_x_mid - active_widget_x_midpoint)) < snapping_sensitivity: return active_widget_x_midpoint - active_widget.get("widget").winfo_width()/2
144 | if(abs((widget_x_mid) - active_widget_x_midpoint + active_widget_width)) < snapping_sensitivity: return active_widget_x_midpoint - active_widget_width - widget_half_x
145 | if(abs((widget_x_mid) - active_widget_x_midpoint - active_widget_width)) < snapping_sensitivity: return active_widget_x_midpoint + active_widget_width - widget_half_x
146 | else:
147 | if(abs(widget_y_mid - active_widget_y_midpoint - active_widget.get("widget").winfo_height() / 2)) < snapping_sensitivity: return active_widget_y_midpoint
148 | if(abs((widget_y_mid - widget_half_y) - active_widget_y_midpoint - active_widget_height)) < snapping_sensitivity: return active_widget_y_midpoint + active_widget_height
149 | if(abs((widget_y_mid - widget_half_y) - active_widget_y_midpoint + active_widget_height)) < snapping_sensitivity: return active_widget_y_midpoint - active_widget_height
150 |
151 | if(test_x and not(export_preferences["Grid Edit Mode:"]["value"])): # testing for app center line
152 | if(abs(widget_x_mid - app.winfo_width()/2) < snapping_sensitivity and not keyboard.is_pressed("alt")): return app.winfo_width()/2 - widget_half_x
153 | else: return False
154 | elif(not(export_preferences["Grid Edit Mode:"]["value"])):
155 | if(abs(widget_y_mid - app.winfo_height()/2) < snapping_sensitivity and not keyboard.is_pressed("alt")): return app.winfo_height()/2 - widget_half_y
156 | else: return False
157 | elif(test_x and (export_preferences["Grid Edit Mode:"]["value"])): # When Grid Mode is Active
158 | app_width = app.winfo_width()
159 | spacing_x = app_width/(export_preferences["Grid Count X:"]["value"] + 1)
160 | for i in range(0, export_preferences["Grid Count X:"]["value"]+1):
161 | if(abs(widget_x_mid - i*spacing_x) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_x - widget_half_x
162 | if(abs((widget_x_mid - widget_half_x) - i*spacing_x) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_x
163 | if(abs((widget_x_mid + widget_half_x) - i*spacing_x) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_x - 2*widget_half_x
164 | return False
165 | elif(not(test_x) and (export_preferences["Grid Edit Mode:"]["value"])): # When Grid Mode is Active
166 | app_height = app.winfo_height()
167 | spacing_y = app_height/(export_preferences["Grid Count Y:"]["value"] + 1)
168 | for i in range(0, export_preferences["Grid Count Y:"]["value"]+1):
169 | if(abs(widget_y_mid - i*spacing_y) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_y - widget_half_y
170 | if(abs((widget_y_mid - widget_half_y) - i*spacing_y) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_y
171 | if(abs((widget_y_mid + widget_half_y) - i*spacing_y) < snapping_sensitivity and not keyboard.is_pressed("alt")): return i*spacing_y - 2*widget_half_y
172 | return False
173 |
174 | def on_drag_motion(event):
175 | widget = event.widget.master
176 | widget_half_height = widget.cget("height") / 2
177 | widget_half_width = widget.cget("width") / 2
178 | x = widget.winfo_x() - widget._drag_start_x + event.x
179 | y = widget.winfo_y() - widget._drag_start_y + event.y
180 |
181 | widget_x_midpoint = x + widget_half_width
182 | widget_y_midpoint = y + widget_half_height
183 |
184 | if(check_other_widgets(widget_x_midpoint, widget_y_midpoint, widget, True, widget_half_width,widget_half_height) and not(keyboard.is_pressed("ctrl"))): # snapping x
185 | x = check_other_widgets(widget_x_midpoint, widget_y_midpoint, widget, True, widget_half_width,widget_half_height)
186 |
187 | if(check_other_widgets(widget_x_midpoint, widget_y_midpoint, widget, False, widget_half_width,widget_half_height) and not(keyboard.is_pressed("ctrl"))): # snapping y
188 | y = check_other_widgets(widget_x_midpoint, widget_y_midpoint, widget, False, widget_half_width,widget_half_height)
189 |
190 | widget.place(x=x, y=y)
191 | for active_widget in active_widgets:
192 | if widget == active_widget.get("widget"):
193 | active_widget['location'] = (int(x),int(y))
194 | break
195 |
196 | def do_popup(event, frame, widget):
197 | global current_widget
198 | try:
199 | ctk.set_default_color_theme('blue')
200 | frame.tk_popup(event.x_root, event.y_root)
201 | current_widget = find_widget_in_active_widgets(widget)
202 | set_theme_to_user_theme()
203 | finally: frame.grab_release()
204 |
205 | def destroy_current_widget():
206 | global current_widget
207 | children_list = current_widget.get("widget").children.copy()
208 | if(children_list is not None):
209 | for children in children_list:
210 | try:
211 | child = find_widget_in_active_widgets((current_widget['widget'].nametowidget((children))))
212 | if(child is not None):
213 | delete_widget_from_frame(child)
214 | except Exception as ex:
215 | ic(ex)
216 |
217 | current_widget.get("widget").destroy()
218 | ctk.set_default_color_theme('blue')
219 | delete_widget_from_frame(current_widget)
220 | set_theme_to_user_theme()
221 |
222 | def update_size_vars(event):
223 | global window_width, window_height, app
224 | if event.widget.widgetName == "toplevel":
225 | if (window_width != event.width) and (window_height != event.height):
226 | window_width.set(event.width)
227 | window_height.set(event.height)
228 | if (keyboard.is_pressed("ctrl")):
229 | width_rounded = math.ceil(event.width/10.0) * 10
230 | height_rounded = math.ceil(event.height/10.0) * 10
231 | window_width.set(width_rounded)
232 | window_height.set(height_rounded)
233 | app.geometry(f"{width_rounded}x{height_rounded}")
234 |
235 | def create_app_window():
236 | global app
237 | if(app is not None):
238 | app.destroy()
239 | app = ctk.CTkToplevel(editor_window)
240 | editor_size,editor_offset_x, editor_offset_y= editor_window.geometry().split("+")
241 | editor_size_x, _ = editor_size.split("x")
242 | app.geometry(f"{entry_width.get()}x{entry_height.get()}+{int(editor_offset_x)+int(editor_size_x) + 10}+{int(editor_offset_y)}") # ensures the window always gets created next to the editor
243 | if(switch_resizable_window.get()):
244 | app.resizable(True, True)
245 | else:
246 | app.resizable(False, False)
247 | app.title(entry_name.get())
248 |
249 | app.bind("", update_size_vars)
250 |
251 | return app
252 |
253 | def apply_window_settings(): # todo, maybe not repeating code here, app shOULDnt HAVE TO BE GLOBAl
254 | global app
255 | if(app == None or app.winfo_exists() == False):
256 | app = create_app_window()
257 | if(combo_theme_selector.get() != ""):
258 | global theme
259 | set_theme_to_user_theme()
260 | app = create_app_window()
261 | if(file_selector.get_path() != ""):
262 | app.after(200, lambda: app.iconbitmap(file_selector.get_path()))
263 | draw_widgets(app, True)
264 | if(entry_width.get() + entry_height.get() != ""):
265 | app.geometry(f"{entry_width.get()}x{entry_height.get()}")
266 | if(entry_name.get() != ""):
267 | app.title(f"{entry_name.get()}")
268 | if(file_selector.get_path() != ""):
269 | if platform.startswith("win"):
270 | app.after(200, lambda: app.iconbitmap(file_selector.get_path()))
271 |
272 | def delete_widget_from_frame(widget):
273 | widget.get('widget').destroy()
274 | frame_widgets.remove_widget(widget.get('widget'))
275 | active_widgets.remove(widget)
276 |
277 | def find_widget_reference_with_name(name):
278 | for widget in active_widgets:
279 | if(widget['widget_id'] == name):
280 | return widget['widget']
281 | return None
282 |
283 | def move_widget_up_in_frame(widget):
284 | ctk.set_default_color_theme('blue')
285 | global active_widgets
286 | widget_index = 0
287 | for active_widget in active_widgets:
288 | if(active_widget.get("widget") == widget.get("widget")):
289 | break
290 | widget_index += 1
291 | if(widget_index == 0):
292 | return
293 | elif(editor_window.nametowidget(active_widgets[widget_index-1]['widget']) != find_widget_reference_with_name(active_widgets[widget_index]['master'])):
294 | active_widgets[widget_index], active_widgets[widget_index - 1] = active_widgets[widget_index - 1], active_widgets[widget_index]
295 | frame_widgets.swap_widget_from_to(widget_index, widget_index-1)
296 | else:
297 | CTkError(editor_window, error_message=f"Widget {active_widgets[widget_index]['widget_id']} cannot be above master {active_widgets[widget_index - 1]['widget_id']}!", button_1_text="Okay", size_x=150, size_y=100)
298 | return
299 | set_theme_to_user_theme()
300 | draw_widgets(app, update_widgets=True, delete_existing_widgets=True)
301 |
302 | def move_widget_down_in_frame(widget):
303 | ctk.set_default_color_theme('blue')
304 | global active_widgets
305 | widget_index = 0
306 | for active_widget in active_widgets:
307 | if(active_widget.get("widget") == widget.get("widget")):
308 | break
309 | widget_index += 1
310 | # ic(widget_index)
311 | if(widget_index == len(active_widgets) - 1):
312 | return
313 | elif(editor_window.nametowidget(active_widgets[widget_index]['widget']) != find_widget_reference_with_name(active_widgets[widget_index + 1]['master'])):
314 | active_widgets[widget_index], active_widgets[widget_index + 1] = active_widgets[widget_index + 1], active_widgets[widget_index]
315 | frame_widgets.swap_widget_from_to(widget_index, widget_index+1)
316 | else:
317 | CTkError(editor_window, error_message=f"Widget {active_widgets[widget_index]['widget_id']} cannot be below child {active_widgets[widget_index + 1]['widget_id']}!", button_1_text="Okay", size_x=150, size_y=100)
318 | return
319 | set_theme_to_user_theme()
320 | draw_widgets(app, update_widgets=True, delete_existing_widgets=True)
321 |
322 | def change_master_overall(widget, new_master):
323 | if(widget['widget'] == new_master['Reference']):
324 | CTkError(editor_window, button_1_text="Okay",error_message="Widget Master Cannot Be Itself!", size_x=150, size_y=100)
325 | raise TypeError("Cannot Set Widget Master To Itself!")
326 | return
327 |
328 | new_master_index = 0
329 | widget_index = 0
330 | for index, active_widget in enumerate(active_widgets):
331 | if(active_widget['widget'] == widget['widget']):
332 | widget_index = index
333 | if(active_widget['widget'] == new_master["Reference"]):
334 | new_master_index = index
335 |
336 | if(new_master_index > widget_index):
337 | CTkError(editor_window, button_1_text="Okay",error_message="Widget master cannot be drawn after child!", size_x=150, size_y=100)
338 | raise TypeError("Widget Master is Lower than Child!")
339 | return
340 | # ic(widget, new_master)
341 | widget['widget'].destroy()
342 | # ic(new_master['Reference'])
343 | widget['master'] = new_master['Name']
344 | widget['location'] = (0, 0)
345 | draw_widgets(app, delete_existing_widgets=True, update_widgets=True)
346 | frame_widgets.update_masters_list(find_frames())
347 |
348 | def find_frames():
349 | frames = []
350 | frames.append({"Name": export_preferences.get("Root Name:")['value'], "Reference": app})
351 | for widget in active_widgets:
352 | if(isinstance(widget['widget'], ctk.CTkFrame)):
353 | frames.append({"Name":widget['widget_id'],"Reference": widget['widget']})
354 | return frames
355 |
356 | def add_bindings(draw=True, updated_menu=None):
357 | for widget_instance in active_widgets: # we want to call these everytime a new widget is added
358 | if(frame_widgets.check_widget(widget_instance.get('widget')) == False):
359 | ctk.set_default_color_theme('blue')
360 | frame_widgets.add_widget(widget_instance,name_change_cb=change_widget_id ,edit_cb=lambda w=widget_instance: open_editor_window(w), masters_list=find_frames(), delete_cb=lambda w=widget_instance: delete_widget_from_frame(w), move_up_cb=lambda w=widget_instance: move_widget_up_in_frame(w), move_down_cb=lambda w=widget_instance: move_widget_down_in_frame(w), change_master_command=change_master_overall)
361 | set_theme_to_user_theme()
362 | if(not(widget_instance.get("has_bindings"))):
363 | widget_instance.get('widget').bind("", lambda event, w=widget_instance.get('widget'): do_popup(event, widget=w, frame=new_right_click_menu(w._nametowidget(w.winfo_parent()))))
364 | widget_instance.get('widget').bind("", lambda event, w=widget_instance: open_editor_window(w))
365 | make_draggable(widget_instance)
366 | widget_instance["has_bindings"] = True
367 | if(draw):
368 | draw_widgets()
369 |
370 | def create_widget(widget_type, duplicate=False, widget_to_duplicate=None, kwarg_list=[],from_file=False, from_file_dict={}, widget_command=None, master=None,**kwargs):
371 | set_theme_to_user_theme()
372 | # Get the widget class from the dictionary
373 | widget_class = widget_types.get(widget_type)
374 | # If the widget type is valid, create the widget and do all the code necessary
375 | if widget_class is not None:
376 | location_x, location_y = ((app.winfo_width()-widget_class(app, **kwargs).cget("width"))/2, (app.winfo_height()-widget_class(app, **kwargs).cget("height"))/2) if not duplicate else widget_to_duplicate.get("location") # if it is duplicated, set the location to middle, otherwise duplicated it on top of the current widget
377 | number_of_same_widgets = 0
378 |
379 | list_of_widgets_names = []
380 | for active_widget in active_widgets:
381 | list_of_widgets_names.append(active_widget["widget_id"])
382 |
383 | for active_widget in active_widgets:
384 | if(active_widget.get("widget_type")) == str(widget_class):
385 | number_of_same_widgets += 1
386 | if(f"{widget_type} {number_of_same_widgets}" not in list_of_widgets_names):
387 | break
388 |
389 | created_widget = {
390 | "widget": None,
391 | "location": (location_x, location_y),
392 | "widget_name": str(widget_type), # todo check why we need this
393 | "widget_type": str(widget_class),
394 | "kwargs": kwargs,
395 | "widget_id": f"{widget_type} {number_of_same_widgets}",
396 | "has_bindings": False,
397 | "master": None
398 | }
399 |
400 | if(master is not None):
401 | created_widget["widget"] = widget_class(find_widget_reference_with_name(master), **kwargs)
402 | created_widget["master"] = master
403 | else:
404 | created_widget["widget"] = widget_class(app, **kwargs)
405 | created_widget["master"] = export_preferences.get("Root Name:")["value"]
406 |
407 | if(widget_type == "Option Menu"):
408 | created_widget.get("widget").configure(state="disabled")
409 | if(duplicate):
410 | created_widget["location"] = (location_x+10, location_y+10)
411 | created_widget["kwargs"] = kwarg_list.copy() # this is needed because image is part of kwargs for some reason
412 | created_widget["command_name"] = widget_command
413 | if("image" in widget_to_duplicate):
414 | created_widget["image_path"] = widget_to_duplicate["image_path"]
415 | created_widget["image_size"] = widget_to_duplicate["image_size"]
416 | edit_widget_attributes(created_widget)
417 | if(from_file):
418 | created_widget["location"] = from_file_dict["location"]
419 | created_widget["kwargs"] = from_file_dict["kwargs"]
420 | created_widget["widget_id"] = from_file_dict["widget_id"]
421 | if("image_path" in from_file_dict):
422 | created_widget["image_path"] = from_file_dict["image_path"]
423 | created_widget["image_size"] = from_file_dict["image_size"]
424 | if("command_name" in from_file_dict):
425 | created_widget["command_name"] = from_file_dict["command_name"]
426 | edit_widget_attributes(created_widget)
427 |
428 | active_widgets.append(created_widget)
429 | add_bindings()
430 |
431 | return created_widget
432 |
433 | def bring_up_a_layer():
434 | global current_widget
435 | move_widget_down_in_frame(current_widget)
436 |
437 | def bring_down_a_layer():
438 | global current_widget
439 | move_widget_up_in_frame(current_widget)
440 |
441 | def new_right_click_menu(master):
442 | RightClickMenu = tk.Menu(master, tearoff=False, background='#565b5e', fg='white', borderwidth=0, bd=0)
443 | RightClickMenu.add_command(label="Duplicate", command=duplicate_current_widget)
444 | RightClickMenu.add_command(label="Edit", command=edit_current_widget)
445 | RightClickMenu.add_command(label="Delete", command=destroy_current_widget)
446 | RightClickMenu.add_command(label="Bring Up One Layer", command=bring_up_a_layer) # todo these are currently reversed in viewport, e.g. higher in active_widgets == drawn first, whereas it should be the opposite
447 | RightClickMenu.add_command(label="Bring Down One Layer", command=bring_down_a_layer)
448 |
449 | return RightClickMenu
450 |
451 | def draw_widgets(new_canvas = None, update_widgets = False, delete_existing_widgets=False):
452 | global background
453 | try:
454 | background
455 | except:
456 | background = None
457 | if(new_canvas):
458 | right_click_menu=new_right_click_menu(new_canvas)
459 |
460 | if(delete_existing_widgets):
461 | for app_widgets in app.winfo_children():
462 | if((app_widgets.nametowidget(app_widgets) != background)):
463 | app_widgets.destroy()
464 | # ic(export_preferences.get('Root Name:')['value'])
465 |
466 | app_ref = new_canvas
467 |
468 | for widget in active_widgets:
469 | if(new_canvas):
470 | kwargs = widget.get('kwargs')
471 | # ic(widget.get('master'))
472 |
473 | if(widget.get('master') != export_preferences.get('Root Name:')['value']):
474 | temp = [i.get('widget') for i in active_widgets if i['widget_id'] == widget.get('master')][0] # reference of master widget
475 | new_canvas = app.nametowidget(str(temp))
476 |
477 | else:
478 | # ic("check passed!")
479 | new_canvas = app_ref
480 | # ic(new_canvas)
481 | widget['widget'] = None
482 | widget['widget'] = widget_types.get((widget.get('widget_name')))(new_canvas, **kwargs)
483 | if('image' in widget):
484 | widget['widget'].configure(image=widget["image"])
485 | if(widget['widget_name'] == "Option Menu"):
486 | widget['widget'].configure(state="disabled")
487 | widget['has_bindings'] = False
488 | widget.get('widget').unbind("")
489 | widget.get('widget').unbind("")
490 | widget.get('widget').unbind("")
491 | widget.get('widget').unbind("")
492 |
493 | x,y = widget.get('location')
494 | widget.get('widget').place(x=x,y=y)
495 | if(update_widgets and not new_canvas):
496 | add_bindings(draw=False)
497 | if(update_widgets and new_canvas):
498 | add_bindings(draw=False, updated_menu=right_click_menu)
499 |
500 | def generate_file(path, export_preferences):
501 | boiler_handler = BoilerPlateHandler()
502 | boiler_handler.set_preferences(export_preferences)
503 | app_height = entry_height.get()
504 | app_width = entry_width.get()
505 |
506 | boiler_handler.check_for_images(active_widgets, file_selector.get_path())
507 | boiler_handler.check_for_commands(active_widgets)
508 |
509 | file_data = ""
510 | try:
511 | if(app_height != "" and app_width != ""):
512 | file_data += boiler_handler.imports()
513 | else:
514 | CTkError(editor_window,error_message="App Dimensions Cannot Be Empty!", button_1_text="Okay")
515 | return
516 |
517 | theme = combo_theme_selector.get().lower()
518 | theme = theme.replace(" ", "-")
519 |
520 | file_data += boiler_handler.basic_app_window(app_width, app_height, file_selector.get_path(), path, entry_name.get(), theme, active_widgets_list=active_widgets)
521 |
522 | for widget in active_widgets:
523 | file_data += (str(boiler_handler.widget_code(widget, path)))
524 |
525 | file_data += boiler_handler.main_loop()
526 |
527 | with open(f"{path}/{export_preferences.get('File Name:')['value']}.py", 'w') as f: # separate f.write functions to not clog down this file any more than it needs to be
528 | f.write(file_data)
529 | CTkError(editor_window,title="Successful!",size_x= 150,size_y=180, error_message=f"Successful write at {path}/{export_preferences.get('File Name:')['value']}.py", button_1_text="Okay")
530 | except Exception as ex:
531 | CTkError(editor_window,error_message=f"Error occured: {ex}\n Please Report On Github", button_1_text="okay", size_x=150, size_y=180)
532 |
533 | def save_logic():
534 | global export_preferences
535 | curr_dir = os.getcwd()
536 | path = filedialog.askdirectory(initialdir=curr_dir)
537 | if(path != ""):
538 | generate_file(path, export_preferences)
539 |
540 | def find_children(widget):
541 | output = []
542 | for widgets in active_widgets:
543 | # ic(widgets["master"])
544 | if(widgets['master'] == widget["widget_id"]):
545 | output.append(widgets)
546 | # ic(output)
547 | return output
548 |
549 | def duplicate_current_widget():
550 | global current_widget
551 | duplicate = create_widget(current_widget.get("widget_name"), True, current_widget, kwarg_list=current_widget.get("kwargs"), widget_command=current_widget.get("command_name"))
552 | if(current_widget['widget_name'] == "Frame"):
553 | for widget in find_children(current_widget):
554 | ic(widget)
555 | create_widget(widget.get("widget_name"), True, widget, kwarg_list=widget["kwargs"], master=duplicate["widget_id"])
556 |
557 | def edit_widget_attributes(widget):
558 | properties = widget.get("kwargs")
559 | if("image_path" in properties):
560 | widget["image_path"] = properties["image_path"]
561 | properties.pop("image_path")
562 | if("image_height" in properties or "image_width" in properties):
563 | widget["image_size"] = (properties["image_width"], properties["image_height"])
564 | properties.pop("image_width")
565 | properties.pop("image_height")
566 | if("command" in properties):
567 | widget["command_name"] = properties["command"]
568 | properties.pop("command")
569 |
570 | try:
571 | widget.get("widget").configure(**properties)
572 | except Exception as ex:
573 | CTkError(editor_window, error_message=f"Error occured: {ex}\n Please Report On Github", button_1_text="Okay", size_x=150, size_y=180)
574 |
575 | if(widget.get("image_path") is not None):
576 | image = ctk.CTkImage(dark_image=Image.open(widget.get("image_path")), size=(widget.get("image_size")))
577 | widget["image"] = image
578 | widget["widget"].configure(image=image)
579 |
580 | def open_editor_window(widget):
581 | ctk.set_default_color_theme('blue')
582 | global attribute_editor_window
583 | if(attribute_editor_window):
584 | # ic("Cheeck")
585 | attribute_editor_window.change_edited_widget(widget)
586 | else:
587 | # ic("FooBar")
588 | attribute_editor_window = AttributeEditorWindow(editor_window, widget_to_edit=widget, apply_settings_cb=edit_widget_attributes, app_pos = (app.winfo_geometry()))
589 | set_theme_to_user_theme()
590 |
591 | def change_widget_id(widget, id):
592 | for widgets in active_widgets:
593 | if (widgets.get("widget_id") == id and widgets != widget):
594 | raise NameError ("There is already an item with this name!")
595 | else:
596 | widget["widget_id"] = id
597 |
598 | def edit_current_widget():
599 | global current_widget
600 | open_editor_window(current_widget)
601 |
602 | def set_preferences(dictionary):
603 | global export_preferences
604 | export_preferences = dictionary
605 |
606 | def export_preferences_editor():
607 | theme = 'blue'
608 | ctk.set_default_color_theme(theme)
609 | export = ExportPreferenceHandler(editor_window, pref_dict=export_preferences)
610 | export.set_set_preferences_cb(lambda: set_preferences(export.get_preferences_dict())) # the button needs a reference to the function to update the export preferences
611 |
612 | def save_as_project(args=None):
613 | global save_path
614 | curr_dir = os.getcwd()
615 | files = [('Json File', '*.json'), ('All Files', '*.*')]
616 |
617 | save_path = (filedialog.asksaveasfile(initialdir=curr_dir, defaultextension=files, filetypes=files, title="Save Project As"))
618 | if(save_path is None):
619 | return
620 | else:
621 | save_path = save_path.name
622 | if(save_path.split('.')[-1] != "json"):
623 | CTkError(editor_window,title="Are you sure?", error_message="Saved type is not a .json. Are you sure what you're doing is worth it?", button_1_text="Yes", size_x=150, size_y=150)
624 | return
625 | if(save_path != ""):
626 | save_project()
627 |
628 | def save_project(args=None):
629 | if(save_path == ""):
630 | save_as_project()
631 | if(save_path is None):
632 | return
633 |
634 | data_to_save = []
635 |
636 | try:
637 | data_to_save = ["This is some data regarding a custom tkinter application"]
638 | data_to_save.append(f"The file has dimensions of ({entry_width.get()}x{entry_height.get()}) and a title of {entry_name.get()}, and has a theme of {combo_theme_selector.get()}. It has an icon path of {file_selector.get_path()}")
639 | for active_widget in active_widgets:
640 | save = [active_widget["widget_name"], active_widget["widget_id"], active_widget["location"], active_widget["kwargs"]]
641 | if("command_name" in active_widget):
642 | save.append(active_widget["command_name"])
643 | else:
644 | save.append(None)
645 | if("image_path" in active_widget):
646 | save.append(active_widget["image_path"])
647 | save.append(active_widget["image_size"])
648 | save.append(active_widget["master"])
649 | data_to_save.append(save)
650 | except Exception as ex:
651 | CTkError(error_message=f"Error occured: {ex}\n Please Report On Github", button_1_text="okay", size_x=200, size_y=120)
652 | return
653 | # so we don't overwrite files if the data isn't generated properly
654 | with open(f"{save_path}", "w") as write_file:
655 | json.dump(data_to_save, write_file, indent=2)
656 |
657 | def open_project(args=None):
658 | global active_widgets
659 | curr_dir = os.getcwd()
660 | file_path = filedialog.askopenfile(initialdir=curr_dir, filetypes=[("Json File","*.json")])
661 | if(file_path is not None):
662 | with open (str(file_path.name), "r") as file:
663 | try:
664 | new_data = json.load(file)
665 | except json.decoder.JSONDecodeError:
666 | CTkError(editor_window, error_message="Bad File!",button_1_text="Okay")
667 | if(new_data[0] != "This is some data regarding a custom tkinter application"):
668 | CTkError(editor_window, error_message="This file is not correct!",button_1_text="Okay")
669 | return
670 | else:
671 | active_widgets = []
672 | frame_widgets.clear_grid()
673 |
674 | width, height = new_data[1].split("(")[1].split(")")[0].split('x') # dealing with window settings data
675 | entry_width.delete(0, (len(str(width)) -1 ))
676 | entry_width.insert(0, int(width))
677 | entry_width.delete(len(str(entry_width.get())) - 1, tk.END)
678 | entry_height.delete(0, (len(str(height)) -1 ))
679 | entry_height.insert(0, int(height))
680 | entry_height.delete(len(str(entry_height.get())) - 1, tk.END)
681 |
682 | title, theme = new_data[1].split("title of ")[1].split(', and has a theme of ')
683 | theme = theme.split(".")[0]
684 | entry_name.delete(0, tk.END)
685 | entry_name.insert(0, title)
686 | combo_theme_selector.set(theme)
687 | ico_path = new_data[1].split("path of ")[1]
688 | try:
689 | if(ico_path != ""):
690 | file_selector.get_entry_element().delete(0, tk.END)
691 | file_selector.get_entry_element().insert(0, ico_path)
692 | except IndexError: # backwards compatibility
693 | pass
694 |
695 | apply_window_settings() # deal with themes
696 |
697 | for item in new_data[2:]: # rest of data is widgets
698 | if(len(item) == 5):
699 | item_dict = {"widget_id": item[1], "location":item[2],"kwargs": item[3]}
700 | elif(len(item)==6):
701 | item_dict = {"widget_id": item[1], "location":item[2],"kwargs": item[3], "command_name": item[4]}
702 | else:
703 | item_dict = {"widget_id": item[1], "location":item[2],"kwargs": item[3], "command_name": item[4], "image_path": item[5], "image_size": tuple(item[6])}
704 | if("font" in item_dict["kwargs"]):
705 | item_dict["kwargs"]["font"] = tuple(item_dict["kwargs"]["font"])
706 | if(find_widget_reference_with_name(item[-1]) is not None):
707 | create_widget(item[0], False, None, from_file=True, from_file_dict=item_dict, master = item[-1])
708 | else:
709 | create_widget(item[0], False, None, from_file=True, from_file_dict=item_dict)
710 |
711 | else:
712 | return
713 |
714 | def validate(action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name):
715 | # if value_if_allowed:
716 | # try:
717 | # int(value_if_allowed)
718 | # return True
719 | # except ValueError:
720 | # return False
721 | # else:
722 | # return False
723 | return True
724 |
725 | def toggle_resize(*args):
726 | if(args):
727 | if(switch_resizable_window.get()):
728 | switch_resizable_window.deselect()
729 | else:
730 | switch_resizable_window.select()
731 | global app
732 | if(switch_resizable_window.get()):
733 | app.resizable(True, True)
734 | else:
735 | app.resizable(False, False)
736 |
737 | ctk.set_appearance_mode("dark")
738 | ctk.set_default_color_theme("blue")
739 |
740 | theme = "blue"
741 |
742 | editor_window = ctk.CTk()
743 | editor_window.geometry("400x530")
744 | editor_window.resizable(width=False, height=False)
745 | editor_window.title("CTKEasyEditor")
746 | icon = ImageTk.PhotoImage(file = 'scripts/assets/icon.png')
747 | editor_window.after(200, lambda: editor_window.iconphoto(False, icon))
748 |
749 | # menubar settings starts
750 | menu = CTkMenuBar(master=editor_window)
751 |
752 | menubar_button_file = menu.add_cascade("File")
753 | menubar_button_edit = menu.add_cascade("Edit")
754 |
755 | dropdown_file = CustomDropdownMenu(widget=menubar_button_file, corner_radius=0)
756 | dropdown_file.add_option(option="Save (ctrl + S)", command=save_project)
757 | editor_window.bind_all("", save_project)
758 | dropdown_file.add_option(option="Save As... (ctrl + shift + S)", command=save_as_project)
759 | editor_window.bind_all("", save_as_project)
760 | dropdown_file.add_option(option="Open Project... (ctrl + O)", command=open_project)
761 | editor_window.bind_all("", open_project)
762 | dropdown_file.add_separator()
763 | dropdown_file.add_option(option="Export as .py", command=save_logic)
764 |
765 | editor_window.bind_all("", toggle_grid)
766 | editor_window.bind_all("", lambda e: change_grid((True, False)))
767 | editor_window.bind_all("", lambda e: change_grid((True, True)))
768 | editor_window.bind_all("", lambda e: change_grid((False, True)))
769 | editor_window.bind_all("", lambda e: change_grid((False, False)))
770 |
771 | dragging = False
772 |
773 | save_path = ""
774 |
775 | dropdown_file = CustomDropdownMenu(widget=menubar_button_edit, corner_radius=0)
776 | dropdown_file.add_option(option="Preferences...", command=export_preferences_editor)
777 | # menubar settings end
778 |
779 | # windows settings starts
780 | label_window_settings = ctk.CTkLabel(editor_window, text="Window Settings")
781 | label_window_settings.pack(anchor="w", padx=15)
782 |
783 | frame_window_settings = ctk.CTkFrame(editor_window, width=380, height=170)
784 |
785 | vcmd = (editor_window.register(validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
786 |
787 | window_width = tk.Variable()
788 | window_height = tk.Variable()
789 |
790 | label_entry_width = ctk.CTkLabel(frame_window_settings, text="px")
791 | label_entry_width.place(x=200, y=10)
792 | label_left_entry_width = ctk.CTkLabel(frame_window_settings, text="Width")
793 | label_left_entry_width.place(x=10, y=10)
794 | entry_width = ctk.CTkEntry(frame_window_settings,placeholder_text = "Width of Window", validate = 'key', validatecommand=vcmd, textvariable=window_width)
795 | entry_width.place(x=55, y=10)
796 | entry_width.insert(0, 500)
797 |
798 | entry_height = ctk.CTkEntry(frame_window_settings, placeholder_text= "Height of Window", validate = 'key', validatecommand=vcmd, textvariable=window_height)
799 | entry_height.place(x=55, y=40)
800 | label_left_entry_height = ctk.CTkLabel(frame_window_settings, text="Height")
801 | label_left_entry_height.place(x=10, y=40)
802 | label_entry_width = ctk.CTkLabel(frame_window_settings, text="px")
803 | label_entry_width.place(x=200, y=40)
804 | entry_height.insert(0, 500)
805 |
806 | entry_name = ctk.CTkEntry(frame_window_settings, placeholder_text= "App Name")
807 | entry_name.place(x=55, y=70)
808 | label_left_name = ctk.CTkLabel(frame_window_settings, text="Title")
809 | label_left_name.place(x=10, y=70)
810 |
811 | file_selector = CTkFileSelector(frame_window_settings,entry_width=115, entry_padding=(20, 5), label="Icon")
812 | file_selector.place(x=10, y=100)
813 |
814 | label_theme_selection = ctk.CTkLabel(frame_window_settings, text="Select a theme:")
815 | label_theme_selection.place(x=250, y=70)
816 | combo_theme_selector = ctk.CTkSegmentedButton(frame_window_settings, values=["Blue", "Dark Blue", "Green"],height=30)
817 | combo_theme_selector.place(x=215, y=100)
818 |
819 | combo_theme_selector.set('Blue')
820 |
821 | button_apply_settings = ctk.CTkButton(frame_window_settings, text="Apply Settings", width=100, height = 60, corner_radius=20, command=apply_window_settings)
822 | button_apply_settings.place(x=250, y = 10)
823 |
824 | switch_resizable_window = ctk.CTkSwitch(frame_window_settings, text="Window Resizable? // Only Editing Window, not final app", command=toggle_resize)
825 | switch_resizable_window.place(x=10, y= 140)
826 |
827 | editor_window.bind_all("", toggle_resize)
828 |
829 | frame_window_settings.pack(pady=0)
830 | # windows settings end
831 |
832 | app = None
833 | app = create_app_window()
834 |
835 | # active widgets ui begins, will reimplement as a tree later: https://github.com/TomSchimansky/CustomTkinter/discussions/524
836 | label_active_widgets = ctk.CTkLabel(editor_window, text="Active Widgets")
837 | label_active_widgets.place(x=15, y=230)
838 | optionmenu_add_widget = ctk.CTkOptionMenu(editor_window, values=[item for item in widget_types.keys()], width = 30, height=20, command=create_widget)
839 | optionmenu_add_widget.place(x=390, y = 243, anchor="e")
840 |
841 | frame_widgets = WidgetHandler(editor_window, width=355, height=250)
842 |
843 | active_widgets = []
844 |
845 | frame_widgets.place(x=10,y=260)
846 | # active widgets ui ends
847 |
848 | current_widget = None
849 |
850 | # Right Click Menu Begins
851 | RightClickMenu = new_right_click_menu(app)
852 | # Right Click Menu Ends
853 |
854 | attribute_editor_window = None
855 | attributes_is_active = False
856 |
857 | app.bind("<1>", lambda event: event.widget.focus_set())
858 |
859 | editor_window.mainloop()
--------------------------------------------------------------------------------
/scripts/preferenceshandler.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 | import tkinter as tk
3 | from icecream import ic
4 |
5 | # this class handles all of the export preferences
6 | # it has a dict with all of the export preferences that we can retrieve
7 | # we pass this dict as an argument to the export handler functions
8 | class ExportPreferenceHandler(ctk.CTkFrame):
9 | def __init__(self, *args, pref_dict=None, **kwargs):
10 | super().__init__(*args, **kwargs)
11 | self.export_settings = pref_dict
12 | self.number_of_settings = len(self.export_settings)
13 |
14 | self.set_cb = None
15 |
16 | self.toplevel = ctk.CTkToplevel()
17 | self.toplevel.geometry(f"300x{self.number_of_settings*30 + 60}")
18 | self.toplevel.attributes('-topmost', 'true')
19 |
20 | self.frame_export_settings = ctk.CTkFrame(self.toplevel, width=280, height=self.number_of_settings*30 + 10)
21 | self.frame_export_settings.place(x=10, y=40)
22 |
23 | self.button_set_preferences = ctk.CTkButton(self.toplevel, text="Set Preferences")
24 | self.button_set_preferences.place(x=150, y=5)
25 |
26 | for index, (key, value) in enumerate(self.export_settings.items()):
27 | label = ctk.CTkLabel(self.frame_export_settings, text=f"{key}")
28 | y_val = (index * 30)+5
29 | label.place(x=10, y=y_val)
30 | if(value.get("cb") is not None): callback = value.get("cb")
31 | else: callback = None
32 |
33 | if(type(value["value"]) == bool):
34 | switch = ctk.CTkSwitch(self.frame_export_settings, text="")
35 | switch.configure(command=lambda k=key, cb = callback, sw=switch: self.set_value(k, bool(sw.get()), cb))
36 | switch.place(x=230, y=y_val)
37 | if(value["value"] == True):
38 | switch.select()
39 | if(type(value["value"]) == str):
40 | textVar = tk.StringVar(value=str(value["value"]))
41 | entry = ctk.CTkEntry(self.frame_export_settings, textvariable=textVar, width=70)
42 | entry.place(x=200, y=y_val)
43 | textVar.trace_add('write', callback=lambda name, index, mode, k=key, t=textVar, cb=callback: self.set_value(k, t.get(), cb))
44 | if(type(value["value"]) == int):
45 | textVar = tk.StringVar(value=int(value["value"]))
46 | entry = ctk.CTkEntry(self.frame_export_settings, textvariable=textVar, width=70)
47 | entry.place(x=200, y=y_val)
48 | textVar.trace_add('write', callback=lambda name, index, mode, k=key, t=textVar, cb=callback: self.set_value(k, t.get(), cb))
49 |
50 | def set_value(self, key_to_set, value_to_set, cb):
51 | self.export_settings[f"{key_to_set}"]["value"] = value_to_set
52 | if(cb is not None):
53 | cb()
54 |
55 | def set_set_preferences_cb(self, cb):
56 | self.button_set_preferences.configure(command=cb)
57 |
58 | def get_preferences_dict(self):
59 | return self.export_settings
60 |
61 |
62 |
--------------------------------------------------------------------------------
/scripts/requirements.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coding-beagle/CTKEasyEditor/4e15840e1996dfe0765fd701ce8367695b51ed52/scripts/requirements.txt
--------------------------------------------------------------------------------
/scripts/settingseditor.py:
--------------------------------------------------------------------------------
1 | import customtkinter as ctk
2 | from CTkFileSelector import *
3 | from icecream import ic
4 | from CTkColorPicker import *
5 | import tkinter as tk
6 |
7 | class AttributeEditorWindow(ctk.CTkFrame):
8 | editable_attributes = {
9 | "Spacer": None,
10 | "Width": {"type": int, "value": 0,"kwarg":"width", "flags": ["px"]},
11 | "Height": {"type": int, "value": 0, "kwarg":"height", "flags": ["px"]},
12 | "Corner Radius": {"type": int, "value": 0,"kwarg":"corner_radius", "flags": ["px"]},
13 | "Border Width": {"type": int, "value": 0,"kwarg":"border_width", "flags": ["px"]},
14 | "Border Spacing": {"type": int, "value": 0,"kwarg":"border_spacing", "flags": ["px"]},
15 | "Checkbox Width": {"type": int, "value": 0,"kwarg":"checkbox_width", "flags": ["px"]},
16 | "Checkbox Height": {"type": int, "value": 0,"kwarg":"checkbox_height", "flags": ["px"]},
17 | "Switch Width": {"type": int, "value": 0,"kwarg":"switch_width", "flags": ["px"]},
18 | "Switch Height": {"type": int, "value": 0,"kwarg":"switch_height", "flags": ["px"]},
19 | "Radio Width": {"type": int, "value": 0,"kwarg":"radiobutton_width", "flags": ["px"]},
20 | "Radio Height": {"type": int, "value": 0,"kwarg":"radiobutton_height", "flags": ["px"]},
21 | "Border Width Checked": {"type": int, "value": 0,"kwarg":"border_width_checked", "flags": ["px"]},
22 | "Border Width Unchecked": {"type": int, "value": 0,"kwarg":"border_width_unchecked", "flags": ["px"]},
23 | "Minimum Pixel Length": {"type": int, "value": 0,"kwarg":"minimum_pixel_length", "flags": ["px"]},
24 | "Foreground Colour": {"type": int, "value": 0,"kwarg":"fg_color", "flags": ["colour"]},
25 | "Hover Colour": {"type": int, "value": 0,"kwarg":"hover_color", "flags": ["colour"]},
26 | "Border Colour": {"type": int, "value": 0,"kwarg":"border_color", "flags": ["colour"]},
27 | "Text Colour": {"type": int, "value": 0,"kwarg":"text_color", "flags": ["colour"]},
28 | "Text Colour Disabled": {"type": int, "value": 0,"kwarg":"text_color_disabled", "flags": ["colour"]},
29 | "Placeholder Text Colour": {"type": int, "value": 0,"kwarg":"placeholder_text_color", "flags": ["colour"]},
30 | "Button Colour": {"type": int, "value": 0,"kwarg":"button_color", "flags": ["colour"]},
31 | "Button Hover Colour": {"type": int, "value": 0,"kwarg":"button_hover_color", "flags": ["colour"]},
32 | "Scrollbar Button Colour": {"type": int, "value": 0,"kwarg":"scrollbar_button_colour", "flags": ["colour"]},
33 | "Scrollbar Button Hover Colour": {"type": int, "value": 0,"kwarg":"scrollbar_button_hover_colour", "flags": ["colour"]},
34 | "Dropdown Foreground Colour": {"type": int, "value": 0,"kwarg":"dropdown_fg_color", "flags": ["colour"]},
35 | "Dropdown Hover Colour": {"type": int, "value": 0,"kwarg":"dropdown_hover_color", "flags": ["colour"]},
36 | "Progress Colour": {"type": int, "value": 0,"kwarg":"progress_color", "flags": ["colour"]},
37 | "Dropdown Text Colour": {"type": int, "value": 0,"kwarg":"dropdown_text_color", "flags": ["colour"]},
38 | "Text": {"type": str, "kwarg":"text", "value": "","flags": []},
39 | "Placeholder Text": {"type": str, "kwarg":"placeholder_text", "value": "","flags": []},
40 | "Font": {"type": tuple, "value": ("Roboto", 0),"kwarg":"font", "flags": [{"dropdown": ["Roboto", "Comic Sans MS","Calibri", "Roman", "Script", "Courier", "Tekton", "Hobot Std"]}, "px"]},
41 | "Dropdown Font": {"type": tuple, "value": (0,0),"kwarg":"dropdown_font", "flags": [{"dropdown": ["Roboto", "Comic Sans MS","Calibri", "Roman", "Script", "Courier", "Tekton", "Hobot Std"]}, "px"]},
42 | "Callback Name": {"type": str, "value": "","kwarg":"command", "flags": ["dontupdate"]},
43 | "Image": {"type": str, "value": "","kwarg": "image_path", "flags": ["dontupdate", "image_path"]},
44 | "Image Width": {"type": int, "value": 0,"kwarg":"image_width","flags":["px"]},
45 | "Image Height": {"type": int, "value": 0,"kwarg":"image_height","flags":["px"]},
46 | "Justify": {"type": str, "value": "", "kwarg": "justify", "flags": [{"dropdown": ["left", "center", "right"]}]},
47 | "Compound": {"type": str, "value": "", "kwarg": "compound", "flags": [{"dropdown": ["top", "bottom", "left", "right"]}]},
48 | "Pad X": {"type": int, "value": 0,"kwarg":"padx", "flags": ["px"]},
49 | "Pad Y": {"type": int, "value": 0, "kwarg":"pady", "flags": ["px"]},
50 | "From": {"type": int, "value": 0, "kwarg":"from_", "flags": []},
51 | "To": {"type": int, "value": 0, "kwarg":"to", "flags": []},
52 | "Number of Steps": {"type": int, "value": 0, "kwarg":"number_of_steps", "flags": []},
53 | "Hover": {"type": bool, "value": True, "kwarg":"hover", "flags": []},
54 | "Dynamic Resizing": {"type": bool, "value": True, "kwarg":"dynamic_resizing", "flags": []},
55 | "Activate Scrollbars": {"type": bool, "value": True, "kwarg":"activate_scrollbars", "flags": []},
56 | "Anchor": {"type": str, "value": "", "kwarg": "anchor", "flags": [{"dropdown": ["n", "s", "e", "w","center"]}]},
57 | "Orientation": {"type": str, "value": "", "kwarg": "orientation", "flags": [{"dropdown": ["horizontal", "vertical"]}]},
58 | "Mode": {"type": str, "value": "", "kwarg": "mode", "flags": [{"dropdown": ["determinate", "indeterminate"]}]},
59 | "Text Wrapping": {"type": str, "value": "", "kwarg": "wrap", "flags": [{"dropdown": ["char","word", "none"]}]},
60 | }
61 |
62 | edit_dict = {
63 | "Button": ["Width", "Height", "Corner Radius", "Border Width", "Spacer", "Text", "Font", "Spacer", "Callback Name", "Spacer", "Image", "Image Width", "Image Height", "Spacer", "Foreground Colour","Hover Colour", "Border Colour", "Text Colour", "Spacer"],
64 | "Label": ["Width", "Height", "Corner Radius", "Spacer", "Text", "Font", "Spacer", "Image", "Image Width", "Image Height", "Spacer", "Foreground Colour", "Text Colour", "Spacer", "Justify", "Compound", "Spacer","Pad X", "Pad Y", "Spacer"],
65 | "Check Box": ["Width", "Height", "Corner Radius", "Border Width", "Spacer", "Text", "Font", "Spacer", "Checkbox Width", "Checkbox Height", "Spacer", "Foreground Colour", "Hover Colour", "Border Colour", "Text Colour", "Spacer"],
66 | "Entry": ["Width", "Height", "Corner Radius", "Spacer", "Text","Placeholder Text", "Font", "Spacer", "Foreground Colour", "Text Colour", "Placeholder Text Colour", "Spacer"],
67 | "Combo Box": ["Width", "Height", "Corner Radius", "Border Width", "Spacer", "Hover", "Justify","Font", "Spacer", "Foreground Colour", "Border Colour","Text Colour", "Text Colour Disabled", "Button Colour", "Button Hover Colour", "Dropdown Foreground Colour", "Dropdown Hover Colour", "Dropdown Text Colour" ,"Spacer"],
68 | "Frame": ["Width", "Height", "Border Width", "Spacer", "Foreground Colour", "Border Colour","Spacer"],
69 | "Option Menu": ["Width", "Height", "Corner Radius", "Spacer", "Hover", "Dynamic Resizing", "Anchor","Font", "Spacer", "Callback Name", "Spacer", "Foreground Colour", "Border Colour","Text Colour", "Text Colour Disabled", "Button Colour", "Button Hover Colour", "Dropdown Foreground Colour", "Dropdown Hover Colour", "Dropdown Text Colour","Spacer"],
70 | "Progress Bar": ["Width", "Height", "Corner Radius", "Border Width", "Spacer", "Mode", "Foreground Colour", "Border Colour", "Progress Colour","Spacer"],
71 | "Radio": ["Width", "Height", "Corner Radius", "Spacer", "Radio Width", "Radio Height", "Border Width Checked", "Border Width Unchecked","Spacer","Text", "Font", "Spacer", "Callback Name","Spacer"],
72 | "Image": ["Image", "Image Width", "Image Height", "Spacer"],
73 | "Scroll Bar": ["Width", "Height", "Corner Radius", "Border Spacing", "Spacer", "Callback Name", "Hover", "Minimum Pixel Length", "Spacer", "Foreground Colour", "Button Colour", "Button Hover Colour", "Spacer"],
74 | "Slider": ["Width", "Height", "Border Width", "Spacer", "Callback Name", "From", "To", "Number of Steps", "Hover", "Spacer", "Foreground Colour", "Progress Colour", "Border Colour", "Button Colour", "Button Hover Colour","Spacer" ],
75 | "Switch": ["Width", "Height", "Corner Radius", "Border Width", "Spacer", "Switch Width", "Switch Height", "Callback Name", "Text","Font","Spacer", "Foreground Colour", "Border Colour", "Progress Colour", "Button Colour", "Button Hover Colour", "Hover Colour", "Text Colour","Spacer"],
76 | "Text Box": ["Width", "Height", "Corner Radius", "Border Width", "Border Spacing", "Spacer", "Text Wrapping","Font","Spacer", "Foreground Colour", "Border Colour", "Text Colour", "Scrollbar Button Colour", "Scrollbar Button Hover Colour","Spacer"],
77 | }
78 |
79 | def __init__(self,*args,widget_to_edit,apply_settings_cb, app_pos,**kwargs):
80 | super().__init__(*args, **kwargs)
81 | self.widget_being_edited = widget_to_edit
82 | self.cb_to_apply = apply_settings_cb
83 |
84 | self.app_position = app_pos
85 | self.app_geometry = (self.app_position.split("+"))
86 | self.app_width, self.app_height = self.app_geometry[0].split("x")
87 | self.editor_offset_x = int(self.app_width) + int(self.app_geometry[1])
88 | self.editor_offset_y = self.app_geometry[2]
89 | self.widget_being_edited = widget_to_edit
90 | self.widget_type = str(widget_to_edit.get("widget_name"))
91 |
92 | self.attributes_to_edit = self.edit_dict.get((self.widget_type))
93 |
94 | self.kwarg_list = {}
95 |
96 | self.toplevel = ctk.CTkToplevel()
97 | self.toplevel.attributes('-topmost', 'true')
98 | self.toplevel.title(f"Widget Properties Editor")
99 | self.toplevel.resizable(False, False)
100 |
101 | self.size_x = 300
102 | self.size_y = 50
103 |
104 | self.label_widget_type = ctk.CTkLabel(self.toplevel,width=50, text=f"Edit {self.widget_being_edited.get('widget_id')}")
105 | self.label_widget_type.cget("font").configure(size=20)
106 | self.label_widget_type.place(x=10,y=10)
107 |
108 | self.button_apply = ctk.CTkButton(self.toplevel, text='Apply Settings', height=30, width=50, corner_radius=10, command=self.update_attributes)
109 | self.button_apply.place(x=190, y=10)
110 |
111 | self.check_attributes(self.attributes_to_edit)
112 |
113 | editor_size, editor_offset_x, editor_offset_y = self.master.geometry().split("+")
114 | # _, editor_size_y = editor_size.split("x")
115 | self.toplevel.geometry(f"{self.size_x}x{self.size_y}+{int(editor_offset_x)+10}+{int(editor_offset_y)}") # ensures the window always gets created below to the editor
116 |
117 | # self.populate_existing_fields()
118 | def update_attributes(self):
119 |
120 | # ic(self.kwarg_list)
121 |
122 | for (value,kwarg) in self.kwarg_list.items():
123 | self.widget_being_edited["kwargs"].update({value:kwarg})
124 |
125 | self.cb_to_apply(self.widget_being_edited)
126 |
127 | def change_edited_widget(self, widget_to_edit):
128 | self.widget_being_edited = widget_to_edit
129 | self.widget_type = (self.widget_being_edited.get("widget_name"))
130 | self.attributes_to_edit = self.edit_dict.get(self.widget_type)
131 | # ic(self.kwarg_list)
132 | self.kwarg_list = {}
133 | self.kwarg_list = self.widget_being_edited['kwargs']
134 | # ic(self.kwarg_list)
135 | # ic(self.widget_being_edited['kwargs'])
136 |
137 | self.size_x = 300
138 | self.size_y = 50
139 | try:
140 | self.toplevel.geometry(f"300x50")
141 | except:
142 | self.toplevel = ctk.CTkToplevel()
143 | self.toplevel.title(f"Widget Properties Editor")
144 | self.toplevel.resizable(False, False)
145 |
146 | editor_size,editor_offset_x, editor_offset_y = self.master.geometry().split("+")
147 | _, editor_size_y = editor_size.split("x")
148 |
149 | self.toplevel.geometry(f"{self.size_x}x{self.size_y}+{int(editor_offset_x) + 200}+{int(editor_offset_y) + 200}")
150 |
151 | for widget in self.winfo_children():
152 | widget.destroy()
153 |
154 | self.label_widget_type = ctk.CTkLabel(self.toplevel,width=50, text=f"Edit {self.widget_being_edited.get('widget_id')}")
155 | self.label_widget_type.cget("font").configure(size=20)
156 | self.label_widget_type.place(x=10,y=10)
157 |
158 | self.button_apply = ctk.CTkButton(self.toplevel, text='Apply Settings', height=30, width=50, corner_radius=10, command=self.update_attributes)
159 | self.button_apply.place(x=190, y=10)
160 |
161 | self.kwarg_list = self.widget_being_edited["kwargs"]
162 |
163 | # ic(self.widget_being_edited['widget_id'])
164 |
165 | self.check_attributes(self.attributes_to_edit)
166 | self.toplevel.geometry(f"{self.size_x}x{self.size_y}")
167 |
168 | def check_attributes(self, attributes_to_edit):
169 | attributes_to_add = []
170 | temp_frame_height = 0
171 | # self.kwarg_list = {}
172 | # self.kwarg_list = self.widget_being_edited['kwargs']
173 |
174 | for attribute in attributes_to_edit:
175 | attribute_info = self.editable_attributes.get(attribute)
176 | if(attribute != "Spacer"): # build up list of attributes to place
177 | attributes_to_add.append(attribute)
178 | if(attribute_info["type"] == tuple):
179 | temp_frame_height += 50
180 | else:
181 | temp_frame_height += 25
182 | else: # clear list of attributes to place
183 | frame = ctk.CTkFrame(self.toplevel, width=280, height=temp_frame_height+12)
184 | frame.place(x=10, y=self.size_y)
185 | for index,additional_attribute in enumerate(attributes_to_add):
186 | info = self.editable_attributes.get(additional_attribute)
187 | y_val = (index*25+5)
188 | flags = self.editable_attributes[additional_attribute]["flags"]
189 | if(info.get('type') == int):
190 | label = ctk.CTkLabel(frame, text=additional_attribute)
191 | label.place(x=10, y=y_val)
192 | textVar = tk.StringVar()
193 | if(info["kwarg"] in self.widget_being_edited['kwargs']): # string var cb logic
194 | textVar.set(self.widget_being_edited['kwargs'][info['kwarg']])
195 | textVar.trace_add(mode='write', callback=lambda name, mode, index, inf=info, tvar=textVar: self.set_value(inf['kwarg'], (tvar.get()), inf['type'], inf["flags"]))
196 | entry = ctk.CTkEntry(frame, placeholder_text=f"{additional_attribute.split(' ')[-1]}", width=50, height=10, textvariable=textVar)
197 |
198 | if("px" in info.get('flags')):
199 | entry.place(x=205, y=y_val+3)
200 | label_px = ctk.CTkLabel(frame, text="px")
201 | label_px.place(x=260, y=y_val)
202 | elif(("colour") in info.get('flags')):
203 | entry = ctk.CTkEntry(frame, placeholder_text=f"#RRGGBB", width=50, height=10, textvariable=textVar)
204 | entry.place(x=200, y=y_val+3)
205 | button_ask_color = ctk.CTkButton(master=frame, text="...", width=20,height=10, command=lambda e=entry: self.set_color(e))
206 | button_ask_color.place(x=255, y=y_val+3)
207 | else:
208 | entry = ctk.CTkEntry(frame, placeholder_text=f"{additional_attribute.lower()}", width=70, height=10)
209 | entry.place(x=205, y=y_val+3)
210 | elif(info.get('type') == str):
211 | label = ctk.CTkLabel(frame, text=additional_attribute)
212 | label.place(x=10, y=y_val)
213 |
214 | textVar = tk.StringVar()
215 | if(info["kwarg"] in self.widget_being_edited['kwargs']):
216 | textVar.set(self.widget_being_edited['kwargs'][info['kwarg']])
217 | textVar.trace_add(mode='write', callback=lambda name, mode, index, inf=info, tvar=textVar: self.set_value(inf['kwarg'], (tvar.get()), inf['type']))
218 | if(any("dropdown" in flag for flag in flags)):
219 | optionmenu = ctk.CTkOptionMenu(frame, width=120, height=17, values=info['flags'][0].get('dropdown'), anchor='w',dynamic_resizing=False)
220 | optionmenu.configure(command= lambda value,inf=info: self.set_value(inf['kwarg'], value, inf['type']))
221 |
222 | optionmenu.place(x=154, y=y_val+3)
223 |
224 | elif("image_path" in info.get('flags')):
225 | entry = ctk.CTkEntry(frame, placeholder_text=f"path/to/img", width=50, height=10, textvariable=textVar)
226 | entry.place(x=200, y=y_val+3)
227 | if("image_path" in self.widget_being_edited):
228 | textVar.set(self.widget_being_edited["image_path"])
229 | button_ask_file = ctk.CTkButton(frame, text="...", width=20, height=10, command=lambda e = entry: self.pick_img(e))
230 | button_ask_file.place(x=255, y=y_val+3)
231 |
232 | else:
233 | entry = ctk.CTkEntry(frame, placeholder_text=f"{additional_attribute.split(' ')[-1]}", width=70, height=10, textvariable=textVar)
234 | entry.place(x=205, y=y_val+3)
235 | elif(info.get('type') == tuple):
236 | if(info.get("kwarg") == "font"):
237 | label = ctk.CTkLabel(frame, text="Font Face")
238 | label.place(x=10, y=y_val)
239 |
240 | optionmenu = ctk.CTkOptionMenu(frame, width=120, height=17, values=info['flags'][0].get('dropdown'), anchor='w',dynamic_resizing=False)
241 | optionmenu.configure(command= lambda value,inf=info: self.set_value(inf['kwarg'], value, inf['type']))
242 | optionmenu.place(x=154, y=y_val+3)
243 |
244 | label = ctk.CTkLabel(frame, text="Font Size")
245 | label.place(x=10, y=y_val+25)
246 |
247 | textVar = tk.StringVar()
248 | if(info["kwarg"] in self.widget_being_edited['kwargs']):
249 | textVar.set(str(abs(int(self.widget_being_edited['kwargs'][info['kwarg']][1]))))
250 | optionmenu.set(self.widget_being_edited['kwargs'][info['kwarg']][0])
251 | textVar.trace_add(mode='write', callback=lambda name, mode, index, inf=info, tvar=textVar: self.set_value(inf['kwarg'], (tvar.get()), inf['type']))
252 |
253 | entry = ctk.CTkEntry(frame, placeholder_text="Font Size", width=70, height=10, textvariable=textVar)
254 | entry.place(x=205, y=y_val+25)
255 | elif(info.get('type') == bool):
256 | label = ctk.CTkLabel(frame, text=additional_attribute)
257 | label.place(x=10, y=y_val)
258 | var = tk.BooleanVar()
259 | if(info['kwarg'] in self.widget_being_edited['kwargs']):
260 | var.set(self.widget_being_edited['kwargs'])
261 |
262 | switch = ctk.CTkSwitch(frame, width=30, height=10,text="", variable=var)
263 | switch.place(x=240, y=y_val+3)
264 |
265 | var.trace_add(mode='write', callback=lambda name,mode,index, v=var, inf=info: self.set_value(inf['kwarg'], bool(v.get()), inf['type']))
266 |
267 | self.size_y += temp_frame_height + 20
268 | temp_frame_height = 0
269 | attributes_to_add = []
270 |
271 | def pick_img(self, entry):
272 | currdir = os.getcwd()
273 | file_path = filedialog.askopenfile(initialdir=currdir)
274 | if(file_path is not None):
275 | entry.delete(0, 'end')
276 | entry.insert(0, file_path.name)
277 |
278 | def set_value(self, key_to_set, value_to_set, vartype, flag=[]):
279 | try:
280 | if(vartype == int and not "dontupdate" in flag and value_to_set):
281 | if('colour' in flag): # todo, check if colour is empty, if it is then pass the default colour value of the theme
282 | # if(value_to_set == ""):
283 | # self.kwarg_list[f"{key_to_set}"] = "DELETEME"
284 | self.kwarg_list[f"{key_to_set}"] = str(value_to_set)
285 | else:
286 | self.kwarg_list[f"{key_to_set}"] = int(value_to_set)
287 | elif(vartype == str and not "dontupdate" in flag and value_to_set):
288 | if(key_to_set == "command_name"):
289 | self.widget_being_edited["command_name"] = value_to_set
290 | else:
291 | self.kwarg_list[f"{key_to_set}"] = (value_to_set)
292 | elif(vartype == tuple and not "dontupdate" in flag and value_to_set):
293 | if(key_to_set == "font" and not value_to_set.isdigit()):
294 | if("font" in self.kwarg_list):
295 | self.kwarg_list[f"{key_to_set}"] = (value_to_set, self.kwarg_list["font"][1])
296 | else:
297 | self.kwarg_list[f"{key_to_set}"] = (value_to_set, 13)
298 | elif(key_to_set == "font" and value_to_set.isdigit()):
299 | if("font" in self.kwarg_list):
300 | self.kwarg_list[f"{key_to_set}"] = (self.kwarg_list["font"][0], -int(value_to_set))
301 | else:
302 | self.kwarg_list[f"{key_to_set}"] = ("roboto", -int(value_to_set))
303 | elif(vartype == bool and not "dontupdate" in flag):
304 | self.kwarg_list[f"{key_to_set}"] = bool(value_to_set)
305 | self.widget_being_edited["kwargs"] = self.kwarg_list ## THIS LINE BREAKS EVERYTHIGN FOR SOME REASOGSDJGsdjkgksn
306 | except ValueError:
307 | pass
308 |
309 | def get_current_widget(self):
310 | return self.widget_being_edited
311 |
312 | def set_color(self, entry_widget):
313 | color = AskColor()
314 | entry_widget.delete(0, 'end')
315 | entry_widget.insert(0, color.get())
--------------------------------------------------------------------------------