Initial Checkin of "readme_creator" folder... the thing that makes the primary readme

This commit is contained in:
MikeTheWatchGuy 2019-07-26 19:35:16 -04:00
parent 59bb9a4fc5
commit 959194fb8e
8 changed files with 5866 additions and 0 deletions

View File

@ -0,0 +1,854 @@
<!--
HOW DO I INSERT IMAGES ???
easy.
■■■ 1 pic at CENTER ■■■
<div align="center" style="padding: 5px;">
<img src="...">
</div>
■■■ N pic, inline, Space around ■■■
<p style="display: flex;justify-content: space-around;">
<img src="...">
</p>
■■■ N pic, inline, padding ■■■
<p style="display: flex;justify-content: space-around;">
<img style="padding:10px;" src="..." >
<img style="padding:10px;" src="..." >
<img style="padding:10px;" src="..." >
</p>
-->
![pysimplegui_logo](https://user-images.githubusercontent.com/13696193/43165867-fe02e3b2-8f62-11e8-9fd0-cc7c86b11772.png)
[![Downloads](http://pepy.tech/badge/pysimplegui)](http://pepy.tech/project/pysimplegui) tkinter
[![Downloads ](https://pepy.tech/badge/pysimplegui27)](https://pepy.tech/project/pysimplegui27) tkinter 2.7
[![Downloads](https://pepy.tech/badge/pysimpleguiqt)](https://pepy.tech/project/pysimpleguiqt) Qt
[![Downloads](https://pepy.tech/badge/pysimpleguiwx)](https://pepy.tech/project/pysimpleguiWx) WxPython
[![Downloads](https://pepy.tech/badge/pysimpleguiweb)](https://pepy.tech/project/pysimpleguiWeb) Web (Remi)
![Documentation Status](https://readthedocs.org/projects/pysimplegui/badge/?version=latest)
![Awesome Meter](https://img.shields.io/badge/Awesome_meter-100-yellow.svg)
![Python Version](https://img.shields.io/badge/Python-2.7_3.x-yellow.svg)
![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_3.x_Version-4.0.0-red.svg?longCache=true&style=for-the-badge)
![Python Version](https://img.shields.io/badge/PySimpleGUI_For_Python_2.7_Version-2.0.0-blue.svg?longCache=true&style=for-the-badge)
![Python Version](https://img.shields.io/badge/PySimpleGUIQt_Version-0.26.0-orange.svg?longCache=true&style=for-the-badge)
![Python Version](https://img.shields.io/badge/PySimpleGUIWx_version-0.11.0-orange.svg?longCache=true&style=for-the-badge)
![Python Version](https://img.shields.io/badge/PySimpleGUIWeb_Version-0.28.1-orange.svg?longCache=true&style=for-the-badge)
# PySimpleGUI
## Python GUIs For Humans - Transforms tkinter, Qt, Remi, WxPython into a people-friendly Pythonic interfaces
## (Non-humans.... PySimpleGUI-Feline port planned for 2020)
## 12-July-2019 Note - This readme is undergoing major changes. It's being released a little early as not all doc strings are completed in the sourcecode.
#### Looking for a GUI package? Are you....
* looking to take your Python code from the world of command lines and into the convenience of a GUI?
* sitting on a Raspberry **Pi** with a touchscreen that's going to waste because you don't have the time to learn a GUI SDK?
* into Machine Learning and are sick of the command line?
* an IT guy/gal that has written some cool tools but due to corporate policies are unable to share unless an EXE file?
* wanting to distribute your Python code to Windows users as a single .EXE file that launches straight into a GUI, much like a WinForms app?
* want to share your program with your friends or families (that aren't so freakish that they have Python running)
* wanting to run a program in your system tray?
* a teacher wanting to teach your students how to program using a GUI?
* a student that wants to put a GUI onto your project that will blow away your teacher?
* looking for a GUI package that is "supported" and is being constantly developed to improve it?
* longing for documentation and scores of examples?
**Look no further, you've found your GUI package**.
#### The basics
* Create windows that look and operate _identically_ to those created directly with tkinter, Qt, WxPython, and Remi.
* Requires 1/2 to 1/10th the amount of code as underlying frameworks.
* One afternoon is all that is required to learn the PySimpleGUI package _and_ write your first custom GUI.
* Students can begin using within their first week of Python education.
* No callback functions. You do not need to write the word `class` _anywhere_ in your code.
* Access to nearly every underlying GUI Framework's Widgets.
* Supports both Python 2.7 & 3 when using tkinter
* Supports both PySide2 and PyQt5 (limited support)
* Effortlessly move across tkinter, Qt, WxPython, and the Web (Remi) by changing only the import statement
* The *only* way to write both desktop and web based GUIs at the same time in Python
* Developed from nothing as a pure Python impelementation with Python friendly interfaces.
* Works with Qt Designer
* Built in Debugger
* Actively maintained and enhanced - 4 ports are underway, all being used by users.
* Corporate as well as home users.
* Appealing to both newcomers to Python and experiened Pythonistas.
* The focus is entirely on the developer and making their life easier, simplified, and in control.
## GUI Development does not have to be difficult nor painful. It can be FUN
#### What users are saying about PySimpleGUI
###### (None of these comments were solicited & are not paid endorsements - other than a huge thank you they received!)
"I've been working to learn PyQT for the past week in my off time as an intro to GUI design and how to apply it to my existing scripts... Took me ~30 minutes to figure out PySimpleGUI and get my scripts working with a GUI."
"Python has been an absolute nightmare for me and I've avoided it like the plague. Until I saw PysimpleGUI."
"I've been pretty amazed at how much more intuitive it is than raw tk/qt. The dude developing it is super active on the project too so if you come across situations that you just can't get the code to do what you want you can make bug/enhancement issues that are almost assured to get a meaningful response."
"This library is the easiest way of gui programming in python! I'm totally in love with it ❤️"
"Wow that readme is extensive and great." (hear the love for docs often)
"Coming from R, Python is absolutely slick for GUIs. PySimpleGUI is a dream."
"I have been writing Python programs for about 4 or 5 months now. Up until this week I never had luck with any UI libraries like Tkinter, Qt, Kivy. I went from not even being able to load a window in Tkinter reliably to making a loading screen, and full program in one night with PySimpleGUI."
"I love PySimpleGUI! I've been teaching it in my Python classes instead of Tkinter."
#### Quick Links To Help and Read Up on the Latest News and Releases
[Homepage - Lastest Readme and Code - GitHub](http://www.PySimpleGUI.com)
[Announcements of Latest Developments, Release news, Misc](https://github.com/PySimpleGUI/PySimpleGUI/issues/142)
[ReadTheDocs](http://www.PySimpleGUI.org) <------ THE best place to read the docs due to TOC, etc. **All** the documentation in **one** place
[COOKBOOK!](http://Cookbook.PySimpleGUI.org)
[Brief Tutorial](https://pysimplegui.readthedocs.io/tutorial/)
[Latest Demos and Master Branch on GitHub](https://github.com/PySimpleGUI/PySimpleGUI)
[Repl.it Home for PySimpleGUI](https://repl.it/@PySimpleGUI)
[Lots of screenshots](https://github.com/PySimpleGUI/PySimpleGUI/issues/1)
#### Python versions
As of 9/25/2018 **both Python 3 and Python 2.7 are supported** when using **tkinter version** of PySimpleGUI! The Python 3 version is named `PySimpleGUI`. The Python 2.7 version is `PySimpleGUI27`. They are installed separately and the imports are different. See instructions in Installation section for more info. **None** of the other ports can use Python 2.
# Platforms
## Hardware and OS Support
PySimpleGUI runs on Windows, Linux and Mac, just like tkinter, Qt, WxPython and Remi do. If you can get the underlying GUI Framework installed / running on your machine then PySimpleGUI will also run there.
### Hardware
* PC's, Desktop, Laptops
* Macs of all types
* Raspberry Pi
* Android devices like phones and tablets
### OS
* Windows 7, 8, 10
* Linux on PC - Tested on **many** distributions
* Linux on Raspbnerry Pi
* Linux on Android - Must use either Termux or PyDroid3
* Mac OS (Sorry I don't know much about Macs)
## Output Devices
In addition to running as a desktop GUI, you can also run your GUI in a web browser by running PySimpleGUIWeb.
This is ideal for "headless" setups like a Raspberry Pi that is at the core of a robot or other design that does not have a normal display screen. For these devices, run a PySimpleGUIWeb program that never exits.
Then connect to your application by going to the Pi's IP address (and port #) using a browser and you'll be in communication with your application. You can use it to make configuration changes or even control a robot or other piece of hardward using buttons in your GUI
## A Complete PySimpleGUI Program (Getting The Gist)
Before diving into details, here's a description of what PySimpleGUI is/does and why that is so powerful.
You keep hearing "custom window" in this document because that's what you're making and using... your own custom windows.
Wouldn't it be nice if a GUI with 3 "rows" of Widgets (Elements) was defined in 3 lines of code? That's exactly how it's done. Each row of Elements are a list. Put all those lists together and you've got a window.
What about handling button clicks and stuff. That's 5 lines of the code below beginning with the while loop.
Now look at the `layout` variable and then look at the window graphic below. Defining a window is taking a design you can see visually and then visually creating it in code. One row of Elements = 1 line of code (can span more if your window is crowded). The window is exactly what we see in the code. A line of text, a line of text and an input area, and finally ok and cancel buttons.
This makes the coding process extremely quick and the amount of code very small
```python
import PySimpleGUI as sg
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [ [sg.Text('Some text on Row 1')],
[sg.Text('Enter something on Row 2'), sg.InputText()],
[sg.OK(), sg.Cancel()]]
# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:
event, values = window.Read()
print(event, values)
if event in (None, 'Cancel'):
break
window.Close()
```
![image](https://user-images.githubusercontent.com/13696193/61077153-cdfc0b00-a3eb-11e9-9e93-d6ec2ffb442a.png)
You gotta admit that the code above is a lot more "fun" looking that tkinter code you've studied before. Adding stuff to your GUI is trivial. You can clearly see the "mapping" of those 3 lines of code to specific Elements laid out in a Window. It's not a trick. It's how easy it is to code in PySimpleGUI.
It's a thrill to complete your GUI project way ahead of what you estimated. Some people take that extra time to polish their GUI to make it even nicer, adding more bells and whistles because it's so easy and it's a lot of fun to see success after success as you write your program.
Others, like IT people and hackers are busily cranking out GUI program after GUI program, and creating tools that others can use. Finally there's an easy way to throw a GUI onto your program and give it to someone. It's a pretty big leap in capability for some people.
Elements are the term used by PySimpleGUI that map to GUI Widgets. A "Text Element" in PySimpleGUI == "Label Widget" in tkinter.
The final bit of magic is in how Elements are created and changed. What about Elements that have settings other than the standard system settings? What if I want my Text to be blue, with a Helverica font on a green background. It's written quite simply:
```python
Text('This is some text', font='Helvetica 12', text_color='blue', background_color='green')
```
As you'll learn in later sections that discuss the parameters to the Elements, there are a LOT of options avilable to you should you choose to use them. The `Text Element` has 15 parameters that you can change. This is one reason why PyCharm is suggested as your IDE... it does a fantastic job of displaying documentation as you type in your code.
## The Underlying GUI Frameworks
At the moment there are 4 acitvely developed and maintained "ports" of PySimpleGUI. These include:
1. tkinter - Fully complete
2. Qt using Pyside2 - Alpha stage. Not all features for all Elements are done
3. WxPython - Development stage, pre-releaser. Not all Elements are done. Some known problems with multiple windows
4. Remi (Web browser support) - Development stage, pre-release.
While PySimpleGUI, the tkinter port, is the only 100% completed version of PySimpleGUI, the other 3 ports have a LOT of functionality in them and are in active use by a large portion of the installations. You can see the number of Pip installs at the very top of this document to get a comparison as to the size of the install base for each port. The "badges" are right after the logo.
# The PySimpleGUI "Family"
## What's The Big Deal? What is it?
PySimpleGUI wraps tkinter, Qt, WxPython and Remi so that you get all the same widgets, but you interact with them in a more friendly way. What does a wrapper do? It does the layout, boilerplate code, creates and manages the GUI Widgets for you and presents you with a **simple, efficient interface.** It replaces the Widgets in tkinter/Qt/Wx/Remi and replaces them with PySimpleGUI Elements. It replaces the GUIs' event loop with one of our own.
You've seen examples of the code already. The big deal of all this is that anyone can create a GUI simply and quickly that matches GUIs written in the native GUI framework. You can create complex layouts with complex element interactions. And, that code you wrote to run on tkinter will also run on Qt by changing your import statement.
## The "Ports"
There are distinct ports happening as mentioned above. Each have their own location on GitHub under the main project. They have their own Readme with is an *augmentation* of this document... they are meant to be used together.
PySimpleGUI is released on PyPI as 5 distinct packages.
1. PySimpleGUI - tkinter version
2. PySimpleGUI27 - tkinter version that runs on 2.7
3. PySimpleGUIWx - WxPython version
4. PySimpleGUIQt - PySided2 version
5. PySimpleGUIWeb - The web (Remi) version
You will need to install them separately
There is also an accompanying debugger known as `imwatchingyou`. If you are running the tkinter version of PySimpleGUI, you will not need to install the debugger as there is a version embedded directly into PySimpleGUI.
## Qt Version
Qt was the second port after tkinter. It is the 2nd most complete with the original PySimpleGUI (tkinter) being the most complete and is likely to continue to be the front-runner.
As mentioned previously each port has an area. For Qt, you can learn more on the [PySimpleGUIQt GitHub site](https://github.com/MikeTheWatchGuy/PySimpleGUI/tree/master/PySimpleGUIQt). **There is a separate Readme file for the Qt version** that you'll find there. This is true for all of the PySimpleGUI ports.
Give it a shot if you're looking for something a bit more "modern". PySimpleGUIQt is currently in Alpha. All of the widgets are operational but some may not yet be full-featured. If one is missing and your project needs it, log an Issue. It's how new features are born.
Here is a summary of the Qt Elements with no real effort spent on design clearly. It's an example of the "test harness" that is a part of each port. If you run the PySimpleGUI.py file itself then you'll see one of these tests.
As you can see, you've got a full array of GUI Elements to work with. All the standard ones are there in a single window. So don't be fooled into thinking PySimpleGUIQt is barely working or doesn't have many widgets to choose from.
![scrolling graphics](https://user-images.githubusercontent.com/13696193/48665874-8bfd0e00-ea84-11e8-880d-8e164d9fea34.gif)
## WxPython Version
[PySimpleGUIWx GitHub site](https://github.com/PySimpleGUI/PySimpleGUI/tree/master/PySimpleGUIWx). **There is a separate Readme file for the WxPython version**.
Started in late December 2018 PySimpleGUIWx started with the SystemTray Icon feature. This enabled the package to have one fully functioning feature that can be used along with tkinter to provide a complete program. The System Tray feature is complete and working very well. It was used not long ago in a corporate setting and has been performing perfectly.
The Windowing code was coming together with Reads operational which means Popups work. The elements were getting completed on a regular basis. But I ran into multiwindow problems. And it was at about this time that Remi was suggested as a port.
Remi (the "web port") overnight lept the WxPython effort and Web became a #1 priority and continues to be. The thought is that the desktop was well represented with PySimpleGUI, PySimpleGUIQt, and PySimpleGUIWx. Between those ports is a solid winowing system and 2 system tray implementations and a nearly feature complete Qt effort. So, the team was switched over.
## Web Version (Remi)
[PySimpleGUIWeb GitHub site](https://github.com/PySimpleGUI/PySimpleGUI/tree/master/PySimpleGUIWeb). **There is a separate Readme file for the Web version**.
New for 2019, PySimpleGUIWeb. This is an exciting development! PySimpleGUI in your Web Browser!
The underlying framework supplying the web capability is the Python package Remi. https://github.com/dddomodossola/remi Remi provides the widgets as well as a web server for you to connect to. It's an exiting new platform to be running on and has temporarily bumped the WxPython port from the highest priority. PySimpleGUIWeb is the current high priority project.
Use this solution for your Pi projects that don't have anything connected in terms of input devices or display. Run your Pi in "headless" mode and then access it via the Web interface. This allows you to easily access and make changes to your Pi without having to hook up anything to it.
## Source code compatibility
Your source code is completely portable from one platform to another by simply changing the import statement. That's the GOAL and if OFTEN the case. I've been stunned how many times thins works. Seeing your code run on tkinter, then change the import to `import PySimpleGUIWeb as sg` and instead of a tkinter window, up pops Chrome with your window running in there instead.
What does this mean? It means it takes a trivial amount of effort to move across GUI Frameworks. Don't like the way your GUI looks on tkinter? No problem, change over to try PySimpleGUIQt. Made a nice desktop app but want to bring it to the web too? Again, no problem, use PySimpleGUIWeb
## repl.it Version
***Want to really get your mind blown?*** Check out this [PySimpleGUI program](https://repl.it/@PySimpleGUI/PySimpleGUIWeb-Demos) running in your web browser.
Thanks to the magic of repl.it and Remi it's possible to run PySimpleGUI code in a browser window without having Python running on your computer.
The programs you write using repl.it will automatically download and install the latest PySimpleGUIWeb from PyPI onto a virtual Python environment. All that is required is to type `import PySimpleGUIWeb` you'll have a Python environment up and running with the latest PyPI release of PySimpleGUIWeb.
This is an exciting new development that's opening up all kinds of possibilities for new ways to program and learn PySimpleGUI. Stayed tuned, much more to be posted about this in the near future.
Educators in particular should be interested. Students can not only post their homework easily for their teacher to access, but teachers can also run the students programs online. No downloading needed. Run it and check the results.
Depending on how you're viewing this document, you may or may not see an embedded browser window below that is running PySimpleGUI code.
Not only can you run PySimpleGUIWeb code using repl.it, they have a tkinter library version. You can see a tkinter (a PySimpleGUI window) in a browser using repl.it.
## Macs
It's surprising that Python GUI code is completely cross platform from Windows to Mac to Linux. No source code changes. This is true for both PySimpleGUI and PySimpleGUIQt.
However, **Macs** suck. They suck on tkinter in particular. The "Look and feel" calls are disabled for Macs. Colored buttons in particular are broken. Not in the PySimpleGUI code, of course. Consider using Qt instead of tkinter on the Mac. Or, if using tkinter, bring your own button images.
I suggest looking through the open and closed issues if you're a Mac person with a problem.
*Switching to "Light Mode" is known to fix some of the problems.* They honestly are tkinter/Mac problems.
Make sure you're running tkinter 8.6 and up.
# Support
PySimpleGUI is an active project. Bugs are fixed, features are added, often. Should you run into trouble, open an issue on the [GitHub site](http://www.PySimpleGUI.com) and you'll receive help. Posting questions on StackOverflow, Forums, Mailing lists, Reddit, etc, is not the fastest path to support and taking it may very well lead you astray as folks not familiar with the package struggle to help you.
So, [open an Issue](https://github.com/PySimpleGUI/PySimpleGUI/issues/new/choose), choose "custom form" and fill it out completely. There are very good reasons behind all of the questions. Cutting corners only cuts your chances of getting help and getting quality help as it's difficult enough to debug remotely. Don't handicap people that want to help by not providing enough information.
Be sure and run your program outside of your IDE *first*. Start your program from the shell using `python` or `python3` command. On numerous occassions much time was spent chasing problems caused by the IDE. By running from a command line, you take that whole question out of the problem, an important step.
### PySimpleGUI Trolls
Yea, they're out there. Would have NEVER in a billion years guessed that there would be objection, coming from a small, but vocal, number of people. I naively believed everyone would be supportive, see the value, hold hands around the fire, sing songs, and in the very least be truthful. But, this ain't Kansas and the Internet is... WTF is it with people?
If someone is actively discouraging you from using this package, then know you are on the right track and you should give it a try. Weird stuff like this sometimes happens because the person works for a particular company or they have a GUI package of their own.... that's not popuplar.
I promise you're not going to be wrecked for life. It will not cause you to be a bad programmer with bad habits. It will not ruin your career. It's not going to teach you bad habits. One person I know got a bonus based on a PySimpleGUI program he wrote. I promise you WILL see a GUI in 5 minutes. And you could see some pretty cool stuff running in a GUI by grabbing the GitHub and start running and hacking on files.
So fear not. ***How about success being the goal?*** Spend time polishing your GUI and working on your primary code instead of struggling your way through the mountains of documentation in the Qt library, trying to set the color of something.
Start with PySimpleGUI, then in the future if you want to code directly in Qt to get more control, it's not like you won't be able to pick up Qt due to your PySimpleGUI knowledge. If anything, you'll have more knowledge going it than most people that are just starting because you'll have already built working GUIs, perhaps many of them.
### Target Audience
PySimpleGUI is trying to serve the 80% of GUI problems. The other 20% go straight onto Qt or WxPython, or whoever fills that need.
PySimpleGUI is designed with both the beginner and the experienceed developer in mind. Why? Because both tend to like compact code as much as I do. Most like people, we just want to get sh\*t done, right?
No, you like the existing GUI architectures (they're all roughly the same, except this one), go join the 20% club just down the street. There's plenty of room for you there. But how about a quick stop-in for some open mindedness exercises. Maybe you will come up with an interesting suggestion even if you don't use it. Or maybe PySimpleGUI does something that inspires you to write something similar directly in Qt.
#### Beginners
There are a couple of reasons beginners stop in for a peek. The first is to simply throw a simple GUI onto the front of an existing command line application. Or maybe you need to popup a box to get a filename. These can often be simple 1-line `Popup` calls.
If you have a more intricate, complete, perhaps multi-window design in mind, then PySimpleGUI still could be your best choice.
This package is not only great to use as your first GUI package, but it also teaches how to design and utilize a GUI. In fact, it does it better than any existing GUI. Why? Because it removes the classes, callback functions, object oriented design to better get out of your way and let you focus entirely on your GUI and not how to represent it in code. The result is 1/2 to 1/10 th the amount of code that implements the exact same layout and widgets as you would get from coding yourself directly in Qt5.
Forget syntax completely and just look on the overall activities of a PySimpleGUI programmer. You have to design your window.... determine your inputs and your outputs, place buttons in strategic places, create menus, .... You'll be busy just doing all those things to design and define your GUI completely independent upon the underlying framework.
#### Advanced Programmers, Code Slingers
It's not perfect, but PySimpleGUI is an amazing bit of technology.
As mentioned, you really can write both a desktop and a web application at the same time, among other things.
What I hear from seasoned professionals is that PySimpleGUI saves them a **ton** of time. They've written GUI code before. They know how to lay out a window. These folks just want to get their window working and quick.
With the help of IDE's like PyCharm, Visual STudio and Wing (the offically supported list) you get instant documentation on the calls you are making. On PyCharm you instantly see both the call signature but also the explanations about each parameter.
Because PySimpleGUI has so many parameters to element creation calls, you really need this level of integration between code and documentation to be able to work quickly.
If the screenshots, demo programs and documentation don't convince you to at least **give it a try, once**, then you're way too busy, or ..... I dunno, I stopped guessing "why?" some time ago. Some of the most reluctant of people to try PySimpleGUI have turned out to be some of the biggest supporters.
-------------------
# Learning Resources
The initial "get up and running" portion of PySimpleGUI should take you less than 5 minutes. The goal is 5 minutes from your decision "I'll give it a try" to having your first window up on the screen "Oh wow, it was that easy?!" in 5 minutes or less.
The primary learning pathes for PySimpleGUI are:
* This readme document over 100 pages of PySimpleGUI answers
* http://www.PySimpleGUI.org
* The Cookbook - Recipes to get you going
* http://Cookbook.PySimpleGUI.org
* The Demo Programs - Start hacking on one of these running soluitions
* http://www.PySimpleGUI.com
* The YouTube videos - If you like instructional videos, there are 15 videos
* [5 part series of basics](https://www.youtube.com/playlist?list=PLl8dD0doyrvHMoJGTdMtgLuHymaqJVjzt)
* [10 part series of more detail](https://www.youtube.com/playlist?list=PLl8dD0doyrvGyXjORNvirTIZxKopJr8s0)
Everything is geared towards giving you a "quick start" whether that be a Recipe or a Demo Program. The idea is to give you something running and let you hack away at it. As a developer this saves tremendous amounts of time.
You **start** with a working program, a GUI on the screen. Then have at it.
A high percentage of users report both learning PySimpleGUI and completing their project in a single day. This isn't a rare event at all. GUI programming doesn't HAVE to be difficult by definition and PySimpleGUI has certainly made it much much more approachable.
## This Readme and Cookbook
The readme and Cookbook are best viewed on ReadTheDocs. The quickest way there is to visit:
http://www.PySimpleGUI.org
You will be auto-forwarded to the right destination. There are multiple tabs on ReadTheDocs. One for the main readme and one for the Cookbook. There are other documents there like an architectural design doc
The Cookbook has approx 27 "Recipes" or short programs that can be easily copied and pastedThe addition of MANY embedded frames of repl.it frames has slowed down the page. I'm questioning the decision to add those embedded frames and may soon remove them.
## Demo Programs
The GitHub repo has the Demo Programs. There are ones built for plain PySimpleGUI that are usually portrable to other versions of PySimpleGUI. And there are some that are associated with one of the other ports. The easiest way to the GitHub:
http://www.PySimpleGUI.com
As of this writing, on 2019-07-10 there are 177 Demo Programs for you to choose from.
These programs demonstrate to you how to use the Elements and especially how to integtate PySimpleGUI with some of the popular open source technologies such as OpenCV, PyGame, PyPlot, and Matplotlib to name a few.
---
# The Quick Tour
Let's take a super-brief tour around PySimpleGUI. There are 2 levels of windowing support in PySimpleGUI - High Level and Customized.
The high-level calls are those that perform a lot of work for you. These are not custom made windows (those are the other way of interacting with PySimpleGUI).
Let's use one of these high level calls, the `Popup` and use it to create our first window, the obligatory "Hello World". It's a single line of code. You can use these calls like print statements, adding as many parameters and types as you desire.
```python
import PySimpleGUI as sg
sg.Popup('Hello From PySimpleGUI!', 'This is the shortest GUI program ever!')
```
![hello world](https://user-images.githubusercontent.com/13696193/44960047-1f7f6380-aec6-11e8-9d5e-12ef935bcade.jpg)
Or how about a ***custom GUI*** in 1 line of code? No kidding this is a valid program and it uses Widgets like you normally would in a tkinter program. It's just been compacted together is all, strictly for demonstration purposes as there's no need to go that extreme in compactness, unless you have a reason to and then you can be thankful you can.
```python
import PySimpleGUI as sg
event, values = sg.Window('Get filename example', [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ]).Read()
```
![get filename](https://user-images.githubusercontent.com/13696193/44960039-f1018880-aec5-11e8-8a43-3d7f8ff93b67.jpg)
------
# Polishing Your Windows = Building "Beautiful Windows"
Your window does not have to look like the boring gray window used in the above example.
So many posts on Reddit asking which GUI is going to result in a "beautiful window", as if there's a magic GUI library that pretties things up for you.
Beautiful windows are created, not simply given to you. There are people that design and create artwork for user interfaces, you know that right? Artists draw buttons, artwork that you include in the window to make it nicer.
These 2 windows are running on top of tkinter. They've been polished and I'm sure they could be polished even further as I'm no artist nor UI expert.
![batterup2](https://user-images.githubusercontent.com/13696193/50378902-6aa2bb00-060a-11e9-8f2f-d746694fa4ee.gif)
![uno_final](https://user-images.githubusercontent.com/13696193/49945232-67952580-feba-11e8-90c8-7dc31c5f7c67.gif)
# Pi Windows
Perhaps you're looking for a way to interact with your **Raspberry Pi** in a more friendly way. Your PySimpleGUI code will run on a Pi with no problem. Tkinter is alive and well on the Pi platform. The controls are a little cruder looking due to the size of the screen, etc. You could add custom artwork, etc to make it look nicer.
This is simply an example of the many GUI Elements that are available to use on all platforms.
![raspberry pi everything demo](https://user-images.githubusercontent.com/13696193/44279694-5b58ce80-a220-11e8-9ab6-d6021f5a944f.jpg)
# Games
It's possible to create some cool games by simply using the built-in PySimpleGUI graphic primivites like those used in this game of pong. PyGame can also be embedded into a PySimpleGUI window and code is provided to you demonstrating how.
![pong](https://user-images.githubusercontent.com/13696193/45860012-2d8d0b00-bd33-11e8-9efd-3eaf4c30f324.gif)
# Windows Programs That Look Like Windows Programs
Do you have the desire to share your code with other people in your department, or with friends and family? Many of them may not have Python on their computer. And in the corporate environment, it may not be possible for you to install Python on their computer.
`PySimpleGUI + PyInstaller` to the rescue!!
Combining PySimpleGUI with PyInstaller creates something truly remarkable and special, a Python program that looks like a Windows WinForms application.
The application you see below with a working menu was created in 20 lines of Python code. It is a single .EXE file that launches straight into the screen you see. And more good news, the only icon you see on the taskbar is the window itself... there is no pesky shell window. Nice, huh?
![menu demo](https://user-images.githubusercontent.com/13696193/45923097-8fbc4c00-beaa-11e8-87d2-01a5331811c8.gif)
With a simple GUI, it becomes practical to "associate" .py files with the python interpreter on Windows. Double click a py file and up pops a GUI window, a more pleasant experience than opening a dos Window and typing a command line.
# Background
Feel free to skip all this if you don't care to know the backstory and reasons behind decisions.
I was frustrated by having to deal with the dos prompt when I had a powerful Windows machine right in front of me. Why is it SO difficult to do even the simplest of input/output to a window in Python??
There was a project looming and a GUI was needed. Thus began a search for a simplified GUI package that would enable me to work with tkinter easier. I found a few, and they were pretty popular too, but they lacked the full-compliment of Widgets and it was impossible to define my own window using those widgets.
A whacky idea came to mind... what if I wrote a simplified GUI and then used THAT to write my application. It would be a lot less code and it would be "easy" to write my application then.
Thus PySimpleGUI was born out of necessity and it's been the necessity of others that have helped evolve it into the package it is today. It would not be 1/2 as good without the help of the community.
Once PySimpleGUI was done, it was time to start working on "the ports". And, of course, also this documentation.
## The Non-OO and Non-Event-Driven Model
How do you make a GUI interface easy enough for first year Python students? Heck, first WEEK of Python was the actual goal and it still is. This meant classes could be used to build and use it, but classes can not be part of the code the user writes. Of course, an OO design is quite possible to use with PySimpleGUI, but it's not a ***requirement***. The sample code and docs stay away from writing new classes for the most part.
What about those pesky callbacks? They're difficult for beginners to grasp and they're a bit of a pain in the ass to deal with. The way PySimpleGUI got around events was to build a "message passing" architecture instead.
Instead of a user function being called when there's some event, instead the information is "passed" to the user when they call the function `Window.Read()` Everything is returned through this call. The callbacks still happen, but they all happen inside of PySimpleGUI where they are turned into messages to pass ot you.
In fact, all of the boilerplate, events, widgets, containers, frames, etc, are exactly the same ones that you would be writing if you wrote directly in tktiner, Qt, .... The full complement of Widgets are available to you via PySimpleGUI Elements. And those widgets are presented to you in a unique and fun way.
### The Result
A GUI that's appealing to a broad audience that is highly customizable, easy to program, and is solid with few bugs and rarely crashes (99% of the time it's some other error that causes a crash).
PySimpleGUI is becoming more and more popular. The number of installs and the number of successes grows daily. Pip installs have exceeded 350,000 in the first year of existance. Over 300 people a day visit the GitHub and the project has 1,800 stars (thank you aweesome users!)
The number of ports is up to 4. The number of integrations with other technologies is constantly being expanded. It's a great time to try PySimpleGUI! You've got no more than 5 or 10 minutes to lose.
# Features
While simple to use, PySimpleGUI has significant depth to be explored by more advanced programmers. The feature set goes way beyond the requirements of a beginner programmer, and into the required features needed for complex GUIs.
For those of you that have heard PySimpleGUI is only good for doing the most simplest of GUIs, this feature list should put that myth to rest. **The SIMPLE part of PySimpleGUI is how much effort _you_ expend to write a GUI. Not the complexity of the program.** It's literally "simple" to do... it is not limited to simple problems.
Features of PySimpleGUI include:
- Support for Python versions 2.7 and 3
- Text
- Single Line Input
- Buttons including these types:
- File Browse
- Files Browse
- Folder Browse
- SaveAs
- Normal button that returns event
- Close window
- Realtime
- Calendar chooser
- Color chooser
- Button Menu
- Checkboxes
- Radio Buttons
- Listbox
- Option Menu
- Menubar
- Button Menu
- Slider
- Spinner
- Dial
- Graph
- Frame with title
- Icons
- Multi-line Text Input
- Scroll-able Output
- Images
- Tables
- Trees
- Progress Bar Async/Non-Blocking Windows
- Tabbed windows
- Paned windows
- Persistent Windows
- Multiple Windows - Unlimited number of windows can be open at the same time
- Redirect Python Output/Errors to scrolling window
- 'Higher level' APIs (e.g. MessageBox, YesNobox, ...)
- Single-Line-Of-Code Proress Bar & Debug Print
- Complete control of colors, look and feel
- Selection of pre-defined palettes
- Button images
- Horizontal and Verticle Separators
- Return values as dictionary
- Set focus
- Bind return key to buttons
- Group widgets into a column and place into window anywhere
- Scrollable columns
- Keyboard low-level key capture
- Mouse scroll-wheel support
- Get Listbox values as they are selected
- Get slider, spinner, combo as they are changed
- Update elements in a live window
- Bulk window-fill operation
- Save / Load window to/from disk
- Borderless (no titlebar) windows (very classy looking)
- Always on top windows
- Menus with ALT-hotkey
- Right click pop-up menu
- Tooltips
- Clickable text
- Transparent windows
- Movable windows
- Animated GIFs
- No async programming required (no callbacks to worry about)
- User expandable by accessing underlying GUI Framework widgets directly
---
## Design Goals
With the developer being the focus, the center of it all, it was important to keep this mindset at all times, including now, today. Why is this such a big deal? Because this package was written so that the universe of Python applications can grow and can **include EVERYONE into the GUI tent.**
> Up in 5 minutes
Success #1 has to happen immediately. Installing and then running your first GUI program. FIVE minutes is the target. The Pip install is under 1 minute. Depending on your IDE and development environment, running your first piece of code could be a copy, paste, and run. This isn't a joke target; it's for real serious.
> Beginers and Advanted Together
Design an interface that both the complete beginner can understand and use that has enough depth that an advanced programmer can make some very nice looking GUIs amd not feel like they're playing with a "toy".
> Success After Success
Success after success.... this is the model that will win developer's hearts. This is what users love about PySimpleGUI. Make your development progress in a way you can run and test your code often. Add a little bit, run it, see it on your screen, smile, move on.
> Copy, Paste, Run.
The Cookbook and Demo Programs are there to fulfill this goal. First get the user seeing on their screen a working GUI that's similar in some way to what they want to create.
If you're wanting to play with OpenCV download the OpenCV Demo Programs and give them a try. Seeing your webcam running in the middle of a GUI window is quite a thrill if you're trying to integrate with the OpenCV package.
"Poof" instant running OpenCV based application == Happy Developer
> Make Simpler Than Expected Interfaces
The Single Line Progress Meter is a good example. It requires one and only 1 line of code. Printing to a debug window is as easy as replacing `print` with `sg.Print` which will route your console output to a scrolling debug window.
> Be Pythonic
Be Pythonic...
This one is difficult for me to define. The code implementing PySimpleGUI isn't PEP8 compliant, but it is consistent. The important thing was what the user saw and experienced while coding, NOT the choices for naming conventioned in the implementation code.
I ended up defining it as - attempt to use language constructs in a natural way and to exploit some of Python's interesting features. Python's lists and optional parameters make PySimpleGUI work smoothly.
- Windows are represented as Python lists of Elements (Term Widget reserved for the underlying GUI Frameworks' representation of the Element)
- A window is a list of rows, and a list of these rows is a window
- Return values are a list/dictionary of button presses and input values
- The SDK calls collapse down into a single line of Python code that presents a custom GUI and returns values should you want that extreme of a single-line soluition
- Elements are all classes. Users interact with elements using class methods but are not required to write their own classes
- Allow keys and other identifiers be any format you want
- While some disagree with the single source file, I find the benefits greatly outweigh the negatives
#### Lofty Goals
> Change Python
The hope is not that ***this*** package will become part of the Python Standard Library. The hope is that Python will become ***the*** go-to language for creating GUI programs that run on Windows, Mac, and Linux *for all levels of developer*. Perhaps this sort of package is needed to make that happen.
> Capture Budding Graphic Designers
The hope is that beginners that are interested in graphic design, and are taking a Python course, will have an easy way to express themselves, right from the start of their Python experience. Even if they're not the best programmers they will be able to show custom GUI layouts with ease.
> Fill the GUI Gap
There is a noticeable gap in the Python GUI solution. Fill that gap and who knows what will happen. At the moment, to make a tradiional GUI window using tkinter, Qt, WxPython and Remi, it takes much more than a week, or a month of Python education to use these GUI packages.
They are out of reach of the beginners. Often WAY out of reach. And yet, time and time again, beginners that say they JUST STARTED with Python will ask on a Forum or Reddit for a GUI pacakage recommendation. 9 times out of 10 Qt is recommended. (smacking head with hand). What a waste of characters. You might as well have just told them, "give up".
> Is There a There?
Maybe there's no "there there". ***Or*** maybe a simple GUI API will enable Python to dominate yet another computing discipline like it has so many others. This is one attempt to find out. So far, it sure looks like there's PLENTY of demand in this area.
# Getting Started with PySimpleGUI
## Installing PySimpleGUI
Of course if you're installing for Qt, WxPython, Web, you'll use PySimpleGUIQt, PySimpleGUIWx, and PySimpleGUIWeb instead of straight PySimpleGUI in the instructions below.
### IDEs
Some IDEs provide virtual environments. PyCharm is one example. For these, you will either use their GUI interface to add packages or use their built-in terminal to do pip installs.
#### Officially Supported IDEs
A number of IDEs have **known problems with PySimpleGUI**. IDLE, Spyder, and Thonny all have problems with intermittent or inconsistent results, especially when a program exits. Any IDE that is based on tkinter is going to have issues with the straight PySimpleGUI port.
The official list of supported IDEs is:
1. PyCharm (or course this is THE IDE to use for use with PySimpleGUI)
2. Wing
3. Visual Studio
### Installing on Python 3
`pip install --upgrade PySimpleGUI`
On some systems you need to run pip3. (Linux and Mac)
`pip3 install --upgrade PySimpleGUI`
On a Raspberry Pi, this is should work:
`sudo pip3 install --upgrade pysimplegui`
Some users have found that upgrading required using an extra flag on the pip `--no-cache-dir`.
`pip install --upgrade --no-cache-dir PySimpleGUI`
On some versions of Linux you will need to first install pip. Need the Chicken before you can get the Egg (get it... Egg?)
`sudo apt install python3-pip`
`tkinter` is a requirement for PySimpleGUI (the only requirement). Some OS variants, such as Ubuntu, do not some with `tkinter` already installed. If you get an error similar to:
`ImportError: No module named tkinter`
then you need to install `tkinter`.
For python 2.7
`sudo apt-get install python-tk`
For python 3
`sudo apt-get install python3-tk`
More information about installing tkinter can be found here: https://www.techinfected.net/2015/09/how-to-install-and-use-tkinter-in-ubuntu-debian-linux-mint.html
### Installing for Python 2.7
`pip install --upgrade PySimpleGUI27`
or
`pip2 install --upgrade PySimpleGUI27`
You may need to also install "future" for version 2.7
`pip install future`
or
`pip2 install future`
Python 2.7 support is relatively new and the bugs are still being worked out. I'm unsure what may need to be done to install tkinter for Python 2.7. Will update this readme when more info is available
Like above, you may have to install either pip or tkinter. To do this on Python 2.7:
`sudo apt install python-pip`
`sudo apt install python-tkinter`
### Testing your installation and Troubleshooting
Once you have installed, or copied the .py file to your app folder, you can test the installation using python. At the command prompt start up Python.
#### The Quick Test
From your commant line type:
`python -m PySimpleGUI`
Of course if you're on Linux/Mac and need to run using the command `python3` then of course type that.
This will display the same window as these instructions:
#### Instructions for Python 2.7:
```python
>>> import PySimpleGUI27
>>> PySimpleGUI27.main()
```
#### Instructions for Python 3:
```python3
>>> import PySimpleGUI
>>> PySimpleGUI.main()
```
You will see a "test harness" that exercises the SDK, tells you the version number, allows you to try
### Finding Out Where Your PySimpleGUI Is Coming From
Sometimes when debugging, questions arise as to exactly which PySimpleGUI you are running. The quick way to find this out is to again, run Python from the command line. This time you'll type:
```python3
>>> import PySimpleGUI as sg
>>> sg
```
When you type sg, Python will tell you the full patch to your PySimpleGUI file / package. This is critical information to know when debugging because it's really easy to forget you've got an old copy of PySimpleGUI laying around somewhere.
### Manual installation
If you're not connected to the net on your target machine, or pip isn't working, or you want to run the latest code from GitHub, then all you have to do is place the single PySimpleGUI source file `PySimpleGUI.py` (for tkinter port) and place it in your application's folder (the folder where the py file is that imports PySimpleGUI). Your application will load that local copy of PySimpleGUI as if it were a package.
Be ***sure*** that you delete this PySimpleGUI.py file if you install a newer pip version. Often the sequence of events is that a bug you've reported was fixed and checked into GitHub. You download the PySimpleGUI.py file (or the appropriately named one for your port) and put with your app. Then later your fix is posted with a new release on PyPI. You'll want to delete the GitHub one before you install from pip.
### Prerequisites
Python 2.7 or Python 3
tkinter
PySimpleGUI Runs on all Python3 platforms that have tkinter running on them. It has been tested on Windows, Mac, Linux, Raspberry Pi. Even runs on `pypy3`.
### EXE file creation
If you wish to create an EXE from your PySimpleGUI application, you will need to install `PyInstaller`. There are instructions on how to create an EXE at the bottom of this document.
## Using - Python 3
To use in your code, simply import....
`import PySimpleGUI as sg`
Then use either "high level" API calls or build your own windows.
`sg.Popup('This is my first Popup')`
![first popup](https://user-images.githubusercontent.com/13696193/44957300-c7813680-ae9e-11e8-9a8c-c70198db7907.jpg)
Yes, it's just that easy to have a window appear on the screen using Python. With PySimpleGUI, making a custom window appear isn't much more difficult. The goal is to get you running on your GUI within ***minutes***, not hours nor days.
## Using - Python 2.7
Those using Python 2.7 will import a different module name
`import PySimpleGUI27 as sg`
## Code to Automatically Import Correct Version
Many of the demo programs use this check to see which package to use:
```python
import sys
if sys.version_info[0] >= 3:
import PySimpleGUI as sg
else:
import PySimpleGUI27 as sg
```
This will automatically import the correct library based on the Python version number reported by the Python interpreter.
---

3312
readme_creator/2_readme.md Normal file

File diff suppressed because it is too large Load Diff

173
readme_creator/3_FOOTER.md Normal file
View File

@ -0,0 +1,173 @@
# "Demo Programs" Applications
There are too many to list!!
There are over 130 sample programs to give you a jump start.
You will find Demo Programs located in a subfolder named "Demo Programs" under each of the PySimpleGUI ports on GitHub.
Demo programs for plain PySimpleGUI (tkinter)
https://github.com/PySimpleGUI/PySimpleGUI/tree/master/DemoPrograms
Demo programs for PySimpleGUIQt:
https://github.com/PySimpleGUI/PySimpleGUI/tree/master/PySimpleGUIQt/Demo%20Programs
Demo programs for PySimpleGUIWx:
https://github.com/PySimpleGUI/PySimpleGUI/tree/master/PySimpleGUIWx/Demo%20Programs
Demo programs for PySimpleGUIWeb:
https://github.com/PySimpleGUI/PySimpleGUI/tree/master/PySimpleGUIWeb/Demo%20Programs
There are not many programs under each of the port's folders because the main Demo Programs should run on all of the other platforms with minimal changes (often only the import statement changes).
## Start Here
When you are just beginning to build your application, or to design it, look through the Demo Programs first to see if there is a program written that does what you're looking for. If so, then this program could be a good starting point. Copy it and modify it to your liking.
Even if no program perfectly matches your situation, there are still a good number of example uses of Elements or techniques that are demonstrated.
Maybe you're going to write a program that uses the Graph Element. In addition to reading the documentaion about the Graph Element, check to see if there's a Demo Program that uses it. At the moment there are 7 Demo programs that match "Demo_Graph_*.py"
## Packages Used In Demos
While the core PySimpleGUI code does not utilize any 3rd party packages, some of the demos do. They add a GUI to a few popular packages. These packages include:
* [Chatterbot](https://github.com/gunthercox/ChatterBot)
* [Mido](https://github.com/olemb/mido)
* [Matplotlib](https://matplotlib.org/)
* [PyMuPDF](https://github.com/rk700/PyMuPDF)
# Creating a Windows .EXE File
It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows.
Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once)
```bash
pip install PySimpleGUI
pip install PyInstaller
```
To create your EXE file from your program that uses PySimpleGUI, `my_program.py`, enter this command in your Windows command prompt:
```bash
pyinstaller -wF my_program.py
```
You will be left with a single file, `my_program.exe`, located in a folder named `dist` under the folder where you executed the `pyinstaller` command.
That's all... Run your `my_program.exe` file on the Windows machine of your choosing.
> "It's just that easy."
(famous last words that screw up just about anything being referenced)
Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar.
If you get a crash with something like:
```python
ValueError: script '.......\src\tkinter' not found
```
Then try adding **`--hidden-import tkinter`** to your command
# Creating a Mac App File
There are reports that PyInstaller can be used to create App files. It's not been officially tested.
Run this command on your Mac
> pyinstaller --onefile --add-binary='/System/Library/Frameworks/Tk.framework/Tk':'tk' --add-binary='/System/Library/Frameworks/Tcl.framework/Tcl':'tcl' your_program.py
This info was located on Reddit with the source traced back to:
https://github.com/pyinstaller/pyinstaller/issues/1350
## Fun Stuff
Here are some things to try if you're bored or want to further customize
**Debug Output**
Be sure and check out the EasyPrint (Print) function described in the high-level API section. Leave your code the way it is, route your stdout and stderror to a scrolling window.
For a fun time, add these lines to the top of your script
```python
import PySimpleGUI as sg
print = sg.Print
```
This will turn all of your print statements into prints that display in a window on your screen rather than to the terminal.
**Look and Feel**
Dial in the look and feel that you like with the `SetOptions` function. You can change all of the defaults in one function call. One line of code to customize the entire GUI.
Or beginning in version 2.9 you can choose from a look and feel using pre-defined color schemes. Call ChangeLookAndFeel with a description string.
```python
sg.ChangeLookAndFeel('GreenTan')
```
Valid values for the description string are:
GreenTan
LightGreen
BluePurple
Purple
BlueMono
GreenMono
BrownBlue
BrightColors
NeutralBlue
Kayak
SandyBeach
TealMono
To see the latest list of color choices, take a look at the bottom of the `PySimpleGUI.py` file where you'll find the `ChangLookAndFeel` function.
You can also combine the `ChangeLookAndFeel` function with the `SetOptions` function to quickly modify one of the canned color schemes. Maybe you like the colors but was more depth to your bezels. You can dial in exactly what you want.
**ObjToString**
Ever wanted to easily display an objects contents easily? Use ObjToString to get a nicely formatted recursive walk of your objects.
This statement:
print(sg.ObjToSting(x))
And this was the output
<class '__main__.X'>
abc = abc
attr12 = 12
c = <class '__main__.C'>
b = <class '__main__.B'>
a = <class '__main__.A'>
attr1 = 1
attr2 = 2
attr3 = three
attr10 = 10
attrx = x
You'll quickly wonder how you ever coded without it.
---
# Known Issues
While not an "issue" this is a ***stern warning***
## **Do not attempt** to call `PySimpleGUI` from multiple threads! It's `tkinter` based and `tkinter` has issues with multiple threads
**Progress Meters** - the visual graphic portion of the meter may be off. May return to the native tkinter progress meter solution in the future. Right now a "custom" progress meter is used. On the bright side, the statistics shown are extremely accurate and can tell you something about the performance of your code. If you are running 2 or more progress meters at the same time using `OneLineProgressMeter`, you need to close the meter by using the "Cancel" button rather than the X
**Async windows** - these include the 'easy' windows (`OneLineProgressMeter` and EasyPrint/Print). If you start overlapping having Async windows open with normal windows then things get a littler squirrelly. Still tracking down the issues and am making it more solid every day possible. You'll know there's an issue when you see blank window.
**EasyPrint** - EasyPrint is a new feature that's pretty awesome. You print and the output goes to a window, with a scroll bar, that you can copy and paste from. Being a new feature, it's got some potential problems. There are known interaction problems with other GUI windows. For example, closing a Print window can also close other windows you have open. For now, don't close your debug print window until other windows are closed too.
## Contributing
A MikeTheWatchGuy production... entirely responsible for this code.... unless it causes you trouble in which case I'm not at all responsible.

View File

@ -0,0 +1,713 @@
## Versions
|Version | Description |
|--|--|
| 1.0.9 | July 10, 2018 - Initial Release |
| 1.0.21 | July 13, 2018 - Readme updates |
| 2.0.0 | July 16, 2018 - ALL optional parameters renamed from CamelCase to all_lower_case
| 2.1.1 | July 18, 2018 - Global settings exposed, fixes
| 2.2.0| July 20, 2018 - Image Elements, Print output
| 2.3.0 | July 23, 2018 - Changed form.Read return codes, Slider Elements, Listbox element. Renamed some methods but left legacy calls in place for now.
| 2.4.0 | July 24, 2018 - Button images. Fixes so can run on Raspberry Pi
| 2.5.0 | July 26, 2018 - Colors. Listbox scrollbar. tkinter Progress Bar instead of homegrown.
| 2.6.0 | July 27, 2018 - auto_size_button setting. License changed to LGPL 3+
| 2.7.0 | July 30, 2018 - realtime buttons, window_location default setting
| 2.8.0 | Aug 9, 2018 - New None default option for Checkbox element, text color option for all elements, return values as a dictionary, setting focus, binding return key
| 2.9.0 | Aug 16,2018 - Screen flash fix, `do_not_clear` input field option, `autosize_text` defaults to `True` now, return values as ordered dict, removed text target from progress bar, rework of return values and initial return values, removed legacy Form.Refresh() method (replaced by Form.ReadNonBlockingForm()), COLUMN elements!!, colored text defaults
| 2.10.0 | Aug 25, 2018 - Keyboard & Mouse features (Return individual keys as if buttons, return mouse scroll-wheel as button, bind return-key to button, control over keyboard focus), SaveAs Button, Update & Get methods for InputText, Update for Listbox, Update & Get for Checkbox, Get for Multiline, Color options for Text Element Update, Progess bar Update can change max value, Update for Button to change text & colors, Update for Image Element, Update for Slider, Form level text justification, Turn off default focus, scroll bar for Listboxes, Images can be from filename or from in-RAM, Update for Image). Fixes - text wrapping in buttons, msg box, removed slider borders entirely and others
| 2.11.0 | Aug 29, 2018 - Lots of little changes that are needed for the demo programs to work. Buttons have their own default element size, fix for Mac default button color, padding support for all elements, option to immediately return if list box gets selected, FilesBrowse button, Canvas Element, Frame Element, Slider resolution option, Form.Refresh method, better text wrapping, 'SystemDefault' look and feel settin
| 2.20.0 | Sept 4, 2018 - Some sizable features this time around of interest to advanced users. Renaming of the MsgBox functions to Popup. Renaming GetFile, etc, to PopupGetFile. High-level windowing capabilities start with Popup, PopupNoWait/PopupNonblocking, PopupNoButtons, default icon, change_submits option for Listbox/Combobox/Slider/Spin/, New OptionMenu element, updating elements after shown, system defaul color option for progress bars, new button type (Dummy Button) that only closes a window, SCROLLABLE Columns!! (yea, playing in the Big League now), LayoutAndShow function removed, form.Fill - bulk updates to forms, FindElement - find element based on key value (ALL elements have keys now), no longer use grid packing for row elements (a potentially huge change), scrolled text box sizing changed, new look and feel themes (Dark, Dark2, Black, Tan, TanBlue, DarkTanBlue, DarkAmber, DarkBlue, Reds, Green)
| 2.30.0 | Sept 6, 2018 - Calendar Chooser (button), borderless windows, load/save form to disk
| 3.0.0 | Sept 7, 2018 - The "fix for poor choice of 2.x numbers" release. Color Chooser (button), "grab anywhere" windows are on by default, disable combo boxes, Input Element text justification (last part needed for 'tables'), Image Element changes to support OpenCV?, PopupGetFile and PopupGetFolder have better no_window option
| 3.01.01 | Sept 10, 2018 - Menus! (sort of a big deal)
| 3.01.02 | Step 11, 2018 - All Element.Update functions have a `disabled` parameter so they can be disabled. Renamed some parameters in Update function (sorry if I broke your code), fix for bug in Image.Update. Wasn't setting size correctly, changed grab_anywhere logic again,added grab anywhere option to PupupGetText (assumes disabled)
| 3.02.00 | Sept 14, 2018 - New Table Element (Beta release), MsgBox removed entirely, font setting for InputText Element, **packing change** risky change that allows some Elements to be resized,removed command parameter from Menu Element, new function names for ReadNonBlocking (Finalize, PreRead), change to text element autosizing and wrapping (yet again), lots of parameter additions to Popup functions (colors, etc).
| 3.03.00 | New feature - One Line Progress Meters, new display_row_numbers for Table Element, fixed bug in EasyProgresssMeters (function will soon go away), OneLine and Easy progress meters set to grab anywhere but can be turned off.
| 03,04.00 | Sept 18, 2018 - New features - Graph Element, Frame Element, more settings exposed to Popup calls. See notes below for more.
| 03.04.01 | Sept 18, 2018 - See release notes
| 03.05.00 | Sept 20, 2018 - See release notes
| 03.05.01 | Sept 22, 2018 - See release notes
| 03.05.02 | Sept 23, 2018 - See release notes
| 03.06.00 | Sept 23, 2018 - Goodbye FlexForm, hello Window
| 03.08.00 | Sept 25, 2018 - Tab and TabGroup Elements\
| 01.00.00 for 2.7 | Sept 25, 2018 - First release for 2.7
| 03.08.04 | Sept 30, 2018 - See release notes
| 03.09.00 | Oct 1, 2018 |
| 2.7 01.01.00 | Oct 1, 2018
| 2.7 01.01.02 | Oct 8, 2018
| 03.09.01 | Oct 8, 2018
| 3.9.3 & 1.1.3 | Oct 11, 2018
| 3.9.4 & 1.1.4 | Oct 16, 2018
| 3.10.1 & 1.2.1 | Oct 20, 2018
| 3.10.3 & 1.2.3 | Oct 23, 2018
| 3.11.0 & 1.11.0 | Oct 28, 2018
| 3.12.0 & 1.12.0 | Oct 28, 2018
| 3.13.0 & 1.13.0 | Oct 29, 2018
| 3.14.0 & 1.14.0 | Nov 2, 2018
| 3.15.0 & 1.15.0 | Nov 20, 2018
| 3.16.0 & 1.16.0 | Nov 26, 2018
| 3.17.0 & 1.17.0 | Dec 1, 2018
## Release Notes
2.3 - Sliders, Listbox's and Image elements (oh my!)
If using Progress Meters, avoid cancelling them when you have another window open. It could lead to future windows being blank. It's being worked on.
New debug printing capability. `sg.Print`
2.5 Discovered issue with scroll bar on `Output` elements. The bar will match size of ROW not the size of the element. Normally you never notice this due to where on a form the `Output` element goes.
Listboxes are still without scrollwheels. The mouse can drag to see more items. The mouse scrollwheel will also scroll the list and will `page up` and `page down` keys.
2.7 Is the "feature complete" release. Pretty much all features are done and in the code
2.8 More text color controls. The caller has more control over things like the focus and what buttons should be clicked when enter key is pressed. Return values as a dictionary! (NICE addition)
2.9 COLUMNS! This is the biggest feature and had the biggest impact on the code base. It was a difficult feature to add, but it was worth it. Can now make even more layouts. Almost any layout is possible with this addition.
.................. insert releases 2.9 to 2.30 .................
3.0 We've come a long way baby! Time for a major revision bump. One reason is that the numbers started to confuse people the latest release was 2.30, but some people read it as 2.3 and thought it went backwards. I kinda messed up the 2.x series of numbers, so why not start with a clean slate. A lot has happened anyway so it's well earned.
One change that will set PySimpleGUI apart is the parlor trick of being able to move the window by clicking on it anywhere. This is turned on by default. It's not a common way to interact with windows. Normally you have to move using the titlebar. Not so with PySimpleGUI. Now you can drag using any part of the window. You will want to turn off for windows with sliders. This feature is enabled in the Window call.
Related to the Grab Anywhere feature is the no_titlebar option, again found in the call to Window. Your window will be a spiffy, borderless window. It's a really interesting effect. Slight problem is that you do not have an icon on the taskbar with these types of windows, so if you don't supply a button to close the window, there's no way to close it other than task manager.
3.0.2 Still making changes to Update methods with many more ahead in the future. Continue to mess with grab anywhere option. Needed to disable in more places such as the PopupGetText function. Any time these is text input on a form, you generally want to turn off the grab anywhere feature.
#### 3.2.0
Biggest change was the addition of the Table Element. Trying to make changes so that form resizing is a possibility but unknown if will work in the long run. Removed all MsgBox, Get* functions and replaced with Popup functions. Popups had multiple new parameters added to change the look and feel of a popup.
#### 3.3.0
OneLineProgressMeter function added which gives you not only a one-line solution to progress meters, but it also gives you the ability to have more than 1 running at the same time, something not possible with the EasyProgressMeterCall
#### 3.4.0
* Frame - New Element - a labelled frame for grouping elements. Similar
to Column
* Graph (like a Canvas element except uses the caller's
coordinate system rather than tkinter's).
* initial_folder - sets starting folder for browsing type buttons (browse for file/folder).
* Buttons return key value rather than button text **If** a `key` is specified,
*
OneLineProgressMeter! Replaced EasyProgressMeter (sorry folks that's
the way progress works sometimes)
* Popup - changed ALL of the Popup calls to provide many more customization settings
* Popup
* PopupGetFolder
* PopupGetFile
* PopupGetText
* Popup
* PopupNoButtons
* PopupNonBlocking
* PopupNoTitlebar
* PopupAutoClose
* PopupCancel
* PopupOK
* PopupOKCancel
* PopupYesNo
#### 3.4.1
* Button.GetText - Button class method. Returns the current text being shown on a button.
* Menu - Tearoff option. Determines if menus should allow them to be torn off
* Help - Shorcut button. Like Submit, cancel, etc
* ReadButton - shortcut for ReadFormButton
#### 3.5.0
* Tool Tips for all elements
* Clickable text
* Text Element relief setting
* Keys as targets for buttons
* New names for buttons:
* Button = SimpleButton
* RButton = ReadButton = ReadFormButton
* Double clickable list entries
* Auto sizing table widths works now
* Feature DELETED - Scaling. Removed from all elements
#### 3.5.1
* Bug fix for broken PySimpleGUI if Python version < 3.6 (sorry!)
* LOTS of Readme changes
#### 3.5.2
* Made `Finalize()` in a way that it can be chained
* Fixed bug in return values from Frame Element contents
#### 3.6.0
* Renamed FlexForm to Window
* Removed LookAndFeel capability from Mac platform.
#### 3.8.0
* Tab and TabGroup Elements - awesome new capabilities
#### 1.0.0 Python 2.7
It's official. There is a 2.7 version of PySimpleGUI!
#### 3.8.2
* Exposed `TKOut` in Output Element
* `DrawText` added to Graph Elements
* Removed `Window.UpdateElements`
* `Window.grab_anywere` defaults to False
#### 3.8.3
* Listbox, Slider, Combobox, Checkbox, Spin, Tab Group - if change_submits is set, will return the Element's key rather than ''
* Added change_submits capability to Checkbox, Tab Group
* Combobox - Can set value to an Index into the Values table rather than the Value itself
* Warnings added to Drawing routines for Graph element (rather than crashing)
* Window - can "force top level" window to be used rather than a normal window. Means that instead of calling Tk to get a window, will call TopLevel to get the window
* Window Disable / Enable - Disables events (button clicks, etc) for a Window. Use this when you open a second window and want to disable the first window from doing anything. This will simulate a 'dialog box'
* Tab Group returns a value with Window is Read. Return value is the string of the selected tab
* Turned off grab_anywhere for Popups
* New parameter, default_extension, for PopupGetFile
* Keyboard shortcuts for menu items. Can hold ALT key to select items in men
* Removed old-style Tabs - Risky change because it hit fundamental window packing and creation. Will also break any old code using this style tab (sorry folks this is how progress happens)
#### 3.8.6
* Fix for Menus.
* Fixed table colors. Now they work
* Fixed returning keys for tabs
* Window Hide / UnHide methods
* Changed all Popups to remove context manager
* Error checking for Graphing objects and for Element Updates
### 3.9.0 & 1.1.0
* The FIRST UNIFIED version of the code!
* Python 2.7 got a TON of features . Look back to 1.0 release for the list
* Tab locations - Can place Tabs on top, bottom, left, right now instead of only the top
### 3.9.1 & 1.1.2
* Tab features
* Themes
* Enable / Disable
* Tab text colors
* Selected tab color
* New GetListValues method for Listbox
* Can now have multiple progress bars in 1 window
* Fix for closing debug-output window with other windows open
* Topanga Look and Feel setting
* User can create new look and feel settings / can access the look and feel table
* New PopupQuick call. Shows a non-blocking popup window with auto-close
* Tree Element partially done (don't use despite it showing up)
### 3.9.3 & 1.1.3
* Disabled setting when creating element for:
* Input
* Combo
* Option Menu
* Listbox
* Radio
* Checkbox
* Spinner
* Multiline
* Buttons
* Slider
* Doc strings on all Elements updated
* Buttons can take image data as well as image files
* Button Update can change images
* Images can have background color
* Table element new num_rows parameter
* Table Element new alternating_row_color parameter
* Tree Element
* Window Disappear / Reappear methods
* Popup buttons resized to same size
* Exposed look and feel table
### 3.9.4 & 1.1.4
* Parameter order change for Button.Update so that new button ext is at front
* New Graph.DrawArc method
* Slider tick interval parameter for labeling sliders
* Menu tearoff now disabled by default
* Tree Data printing simplified and made prettier
* Window resizable parameter. Defaults to not resizable
* Button images can have text over them now
* BUG fix in listbox double-click. First bug fix in months
* New Look And Feel capability. List predefined settings using ListOfLookAndFeelValues
### 3.10.1 & 1.2.1
* Combobox new readonly parameter in init and Update
* Better default sizes for Slider
* Read of Tables now returns which rows are selected (big damned deal feature)
* PARTIAL support of Table.Update with new values (use at your own peril)
* Alpha channel setting for Windows
* Timeout setting for Window.Read (big damned deal feature)
* Icon can be base64 image now in SetIcon call
* Window.FindElementWithFocus call
* Window.Move allows moving window anywhere on screen
* Window.Minimize will minimize to taskbar
* Button background color can be set to system default (i.e. not changed)
### 3.10.2 & 1.2.2
Emergency patch release... going out same day as previous release
* The timeout timer for the new Read with timer wasn't being properly shut down
* The Image.Update method appears to not have been written correctly. It didn't handle base64 images like the other elements that deal with images (buttons)
### 3.10.3 & 1.2.3
* New element - Vertical Separator
* New parameter for InputText - change_submits. If True will cause Read to return when a button fills in the InputText element
* Read with timeout = 0 is same as read non blocking and is the new preferred method
* Will return event == None if window closed
* New Close method will close all window types
* Scrollbars for Tables automatically added (no need for a Column Element)
* Table Update method complete
* Turned off expand when packing row frame... was accidentally turned on (primary reason for this release)
* Try added to Image Update so won't crash if bad image passed in
### 3.11.0 & 1.11.0
* Syncing up the second digit of the releases so that they stay in sync better. the 2.7 release is built literally from the 3.x code so they really are the same
* Reworked Read call... significantly.
* Realtime buttons work with timeouts or blocking read
* Removed default value parm on Buttons and Button Updates
* New Tree Element parm show_expanded. Causes Tree to be shown as fully expanded
* Tree Element now returns which rows are selected when Read
* New Window method BringToFront
* Shortcut buttons no longer close windows!
* Added CloseButton, CButton that closes the windows
### 3.12.0 & 1.12.0
* Changed Button to be the same as ReadButton which means it will no longer close the window
* All shortcut buttons no longer close the window
* Updating a table clears selected rows information in return values
* Progress meter uses new CloseButton
* Popups use new CloseButton
### 3.13.0 & 1.13.0
* Improved multiple window handling of Popups when the X is used to close
* Change submits added for:
* Multiline
* Input Text
* Table
* Tree
* Option to close calendar chooser when date selected
* Update for Tree Element
* Scroll bars for Trees
### 3.14.0 & 1.14.0
* More windowing changes...
* using a hidden root windowing (Tk())
* all children are Toplevel() windows
* Read only setting for:
* Input Text
* Multiline
* Font setting for InputCombo, Multiline
* change_submits setting for Radio Element
* SetFocus for multiline, input elements
* Default mon, day, year for calendar chooser button
* Tree element update, added ability to change a single key
* Message parm removed from ReadNonBlocking
* Fix for closing windows using X
* CurrentLocation method for Windows
* Debug Window options
* location
* font
* no_button
* no_titlebar
* grab_anywhere
* keep_on_top
* New Print / EasyPrint options
* location
* font
* no_button
* no_titlebar
* grab_anywhere
* keep_on_top
* New popup, PopupQuickMessage
* PopupGetFolder, PopupGetFile new initial_folder parm
### 3.15.0 & 1.15.0
* Error checking for InputText.Get method
* Text color, background color added to multiline element.Update
* Update method for Output Element - gives ability to clear the output
* Graph Element - Read returns values if new flages set
* Change submits, drag submits
* Returns x,y coordinates
* Column element new parm vertical_scroll_only
* Table element new parm - bind return key - returns if return or double click
* New Window parms - size, disable_close
* "Better" multiwindow capabilities
* Window.Size property
* Popups - new title parm, custom_text
* title sets the window title
* custom_text - single string or tuple string sets text on button(s)
### 3.16.0 & 1.16.0
* Bug fix in PopupScrolled
* New `Element` shortcut function for `FindElement`
* Dummy Stretch Element made for backwards compatibility with Qt
* Timer function prints in milliseconds now, was seconds
### 3.17.0 &1.17.0 2-Dec-2018
3.17.0 2-Dec-2017
* Tooltip offset now programmable. Set variable DEFAULT_TOOLTIP_OFFSET. Defaults to (20,-20)
* Tooltips are always on top now
* Disable menu items
* Menu items can have keys
* StatusBar Element (preparing for a real status bar in Qt)
* enable_events parameter added to ALL Elements capable of generating events
* InputText.Update select parameter will select the input text
* Listbox.Update - set_to_index parameter will select a single items
* Menus can be updated!
* Menus have an entry in the return values
* LayoutAndRead depricated
* Multi-window support continues (X detection)
* PopupScrolled now has a location parameter
* row_height parameter to Table Element
* Stretch Element (DUMMY) so that can be source code compatible with Qt
* ButtonMenu Element (DUMMY) so can be source code compat with Qt. Will implement eventually
## 3.18.0 11-Dec-2018
NOTE - **Menus are broken** on version 2.7. Don't know how long they've been this way. Please get off legacy Python if that's what you're running.
* Default progress bar length changed to shorter
* Master window and tracking of num open windows moved from global to Window class variable
* Element visibility setting (when created and when Updating element)
* Input text visiblity
* Combo visiblity
* Combo replaces InputCombo as the primary class name
* Option menu visibility
* Listbox visiblity
* Listbox new SetFocus method
* Radio visibility
* Checkbox visibility
* Spin visiblity
* Spin new Get method returns current value
* Multiline visiblity
* Text visibility
* StatusBar visiblity
* Output visibility
* Button visibility
* Button SetFocus
* ProgressBar - New Update method (used only for visibility)
* Image - clickable images! enable_events parameter
* Image visibility
* Canvas visibility
* Graph visibility
* Graph - new DrawImage capability (finally)
* Frame visibility
* Tab visibility (may not be fully functional)
* TabGroup visibility
* Slider visibility
* Slider - new disable_number_display parameter
* Column visibilty
* Menu visibility - Not functional
* Table visibility
* Table - new num_rows parm for Update - changes number of visible rows
* Tree visiblity
* Window - New element_padding parameter will get padding for entire window
* OneLineProgressMeter - Completely REPLACED the implementation
* OneLineProgressMeter - can get reason for the cancellation (cancel button versus X)
* EasyProgressMeter - completely removed. Use OneLineProgressMeter instead
* Debug window, EasyPrint, Print - debug window will re-open if printed to after being closed
* SetOptions - can change the error button color
* Much bigger window created when running PySimpleGUI.py by itself. Meant to help with regression testing
## 3.19.2 13-Dec-2018
* Warning for Mac's when trying to change button color
* New parms for Button.Update - image_size and image_subsample
* Buttons - remove highlight when border depth == 0
* OneLineProgressMeter - better layout implementation
## 3.20.0 & 1.20.0 18-Dec-2018
* New Pane Element
* Graph.DeleteFigure method
* disable_minimize - New parameter for Window
* Fix for 2.7 menus
* Debug Window no longer re-routes stdout by default
* Can re-route by specifying in Print / EasyPrint call
* New non-blocking for PopupScrolled
* Can set title for PopupScrolled window
## 3.21.0 & 1.21.0 28-Dec-2018
* ButtonMenu Element
* Embedded base64 default icon
* Input Text Right click menu
* Disabled Input Text are now 'readonly' instead of disabled
* Listbox right click menu
* Multiline right click menu
* Text right click menu
* Output right click menu
* Image right click menu
* Canvas right click menu
* Graph right click menu
* Frame right click menu
* Tab, tabgroup right click menu (unsure if works correctly)
* Column right click menu
* Table right click menu
* Tree right click menu
* Window level right click menu
* Window icon can be filename or bytes (Base64 string)
* Window.Maximize method
* Attempted to use Styles better with Combobox
* Fixed bug blocking setting bar colors in OneLineProgressMeter
# 3.22.0 PySimpleGUI / 1.22.0 PySimpleGUI27
* Added type hints to some portions of the code
* Output element can be made invisible
* Image sizing and subsample for Button images
* Invisibility for ButtonMenusup
* Attempt at specifying size of Column elements (limited success)
* Table Element
* New row_colors parameter
* New vertical_scroll_only parameter - NOTE - will have to disable to get horizontal scrollbars
* Tree Element
* New row_height parameter
* New feature - Icons for tree entries using filename or Base64 images
* Fix for bug sending back continuous mouse events
* New parameter silence_on_error for FindElement / Element calls
* Slider returns float now
* Fix for Menus when using Python 2.7
* Combobox Styling (again)
# 3.2.0 PySimpleGUI / 1.23.0 PySimpleGUI27 16-Jan-2019
* Animated GIFs!
* Calendar Chooser stays on top of other windows
* Fixed bug of no column headings for Tables
* Tables now use the font parameter
# 3.24.0 1.24.0 16-Jan-2019
* PopupAnimated - A popup call for showing "loading" type of windows
# 3.25 & 1.25 20-Feb-2019
* Comments :-)
* Convert Text to string right away
* Caught exceptions when main program shut down with X
* Caught exceptions in all of the graphics primitives
* Added parameter exportselection=False to Listbox so can use multiple listboxes
* OneLineProgressMeter - Can now change the text on every call if desired
## 3.27.0 PySimpleGUI 31-Mar-2019
Mixup.... 3.26 changes don't appear to have been correctly released so releasing in 3.27 now
* do_not_clear now defaults to TRUE!!!
* Input Element
* Multiline Element
* Enable Radio Buttons to be in different containers
* Ability to modify Autoscroll setting in Multiline.Update call
* PopupGetFolder, PopupGetFile, PopupGetText - title defaults to message if none provided
* PopupAnimated - image_source can be a filename or bytes (base64)
* Option Menu can now have values updated
## 3.28.0 11-Apr-2019 PySimpleGUI
* NEW Window Parameter - layout - second parameter. Can pass in layout directly now!
* New shortcuts
* I = InputText
* B = Btn = Butt = Button
* Convert button text to string when creating buttons
* Buttons are returned now as well as input fields when searching for element with focus
## 3.29 22-Apr-2019
* New method for `Graph` - `RelocateFigure`
* Output Element no longer accepts focus
## 3.32.0 PySimpleGUI 24-May-2019
* Rework of ALLL Tooltips. Was always displaying at uttuper left part of element. Not displays closer to where mouse entered or edited
* New Element.Widget base class variable. Brings tkinter into the newer architecture of user accessibility to underlying GUI Frameworks' widgets
* New SetTooltip Element method. Means all Elements gain this method. Can set the tooltip on the fly now for all elements
* Include scroll bar when making visible / invisible Listbox Elements
* New Radio Element method - `Radio.ResetGroup()` sets all elements in the Radio Group to False* Added borderwidth to Multiline Element
* `Button.Click()` - new method - Generates a button click even as if a user clicked a button (at the tkinter level)
* Made a Graph.Images dictionary to keep track of images being used in a graph. When graph is deleted, all of the accociated images should be deleted too.'
* Added `Graph.SetFocus()` to give a Graph Element the focus just as you can input elements
* Table new parameter - `hide_vertical_scroll` if True will hide the table's vertical bars
* Window - new parameter - `transparent_color`. Causes a single color to become completely transparent such that you see through the window, you can click through the window. Its like tineows never was there.
* The new `Window.AllKeysDict = {}` has been adopted by all PySimpleGUI ports. It's a new method of automatically creating missing keys, storing and retrieving keys in general for a window.
* Changed how `window.Maximize` is implemented previously used the '-fullscreen' attribute. Now uses the 'zoomed' state
* Window gets a new `Normal()` method to return from Maximize state. Sets root.state('normal')
* Window.Close() now closes the special `Window.hidden_master_root` window when the "last" window is closed
* `Window.SetTransparentColor` method added. Same effect as if window was created with parameter set
* An Element's Widget stored in `.Widget` attribute
* Making ComboBox's ID unique by using it's Key
* Changed Multiline to be sunken and have a border depth setting now
* Removed a second canvas that was being used for Graph element.
* Changed how no titlebar is implemented running on Linux versus Windows. -type splash now used for Linux
* PopupScrolled - Added back using CloseButton to close the window
* Fixed PopupGetFolder to use correct PySimpleGUI program constructs (keys)
* PopupGetText populated values carrectly using the value variable, used keys
* PopupAnimated finally gets a completely transparent background
## 3.33.0 and 1.33 PySimpleGUI 25-May-2019
* Emergency fix due to debugger. Old bug was that Image Element was not testing for COLOR_SYSTEM_DEFAULT correctly.
## 3.34.0 PySimpleGUI & 1.34.0 PySimpleGUI27 25-May-2019
pip rhw w cenf
* Fixed Window.Maximize and Window.Normal - needed special code for Linux
* Check for DEFAULT_SCROLLBAR_COLOR not being the COLOR_SYSTEM_DEFAULT (crashed)
## 3.35 PySimpleGUI & 1.35 PySimpleGUI27 27-May-2019
* Bug fix - when setting default for Checkbox it was also disabling the element!
## 3.36 PySimpleGUI & 1.36 PySimpleGUI27 29-May-2019
A combination of user requests, and needs of new `imwatchingyou` debugger
* New Debugger Icon for future built-in debugger
* Fixed bug in FindBoundReturnKey - needed to also check Panes
* NEW Window functions to turn on/off the Grab Anywhere feature
* `Window.GrabAnyWhereOn()`
* `Window.GrabAnyWhereOff()`
* New "Debugger" button that's built-in like other buttons. It's a TINY button with a logo. For future use when a debugger is built into PySimpleGUI itself (SOON!)
* Change Text Element Wrap Length calculation. Went fromn +40 pixels to +10 pixels in formula
* PopupGetFile has new parameter - `multiple_files`. If True then allows selection of multiple files
## 3.37 PySimpleGUI & 1.37 PySimpleGUI27 1-June-2019
* The built-in debugger is HERE - might not WORK exactly yet, but a lot of code went into te PySimpleGUI.py file for this. At the moment, the `imwatchingyou` package is THE way to use a PySimpleGUI debugger. But soon enough you won't need that project in order to debug your program.
* Some strange code reformatting snuck in. There are 351 differences between this and previous release. I'm not sure what happened but am looking at every change by hand.
* New Calendar Button features
* locale, format - new parameters to TKCalendar call
* Use custom icon for window if one has been set
* New parameters to CalendarButton - `locale`, `format`
* The bulk of the built-in PySimpleGUI debugger has been added but is not yet "officially supported". Try pressing "break" or "ctrl+break" on your keyboard.
* New bindings for break / pause button and debugger
* New Debug button will launch debugger.
* New parameter `debugger_enabled` added to Window call. Default is __enabled__.
* Your progam's call to Read is all that's needed to refresh debugger
* New `Window` methods to control debugger access
* `EnableDebugger` - turns on HOTKEYS to debugger
* `DisableDebugger` - turns off HOTKEYS to debugger
* Restored wrap len for Text elements back from +10 to +40 pixels
* `PopupGetFolder`, `PopupGetFile` - fixed so that the "hidden" master window stays hidden (a Linux problem)
* Added support for Multiple Files to `PopupGetFiles` when no_window option has been set.
## 3.38 PySimpleGUI, 1.38 PySimpleGUI27
* Multiline - now has a "read only" state if created as "Disabled"
* Multiline - If window is created as resizable, then Multiline Elements will now expand when the window is enlarged, a feature long asked for.
* Output Element expands in the Y Direction
* "Expandable Rows" option added to PackFormIntoFrame allowing future elements to also expand
* Error Element - silence_on_error option
* Text Element wrapping - FINALLY got it right? No more "Fudge factor" added
* PopupScrolled - Windows are now resizable
* Option to "launch built-in debugger" from the test harness
* Rememeber that the Debugger is still in this code! It may or may not be operational as it's one version back from the latest release of the `imwatchingyou` debugger code. This code needs to be integrated back in
## 3.39 PySimpleGUI & 1.39 PySimpleGUI27 13-June-2019
* Ported the imwatchingyou debugger code into PySimpleGUI code
* Replaced old debugger built-in code with the newer imwatchingyou version
* Required removing all of the 'sg.' before PySimpleGUI calls since not importing
* Dynamically create the debugger object when first call to `refresh` or `show` is made
* Started the procecss of renaming Class Methods that are private to start with _
* Needed for the automatic documentation generation that's being worked on
* Fixed crash when clicking the Debug button
* Fixed bug in DeleteFigure. Needed to delete image separately
* Added more type hints
* New `TabGroup` method `SelectTab(index)` selects a `Tab` within a `TabGroup`
* New `Table.Update` parameter - `select_rows`. List of rows to select (0 is first)
* Error checking in `Window.Layout` provides error "hints" to the user
* Looks for badly placed ']'
* Looks for functions missing '()'
* Pops up a window warning user instead of crashing
* May have to revisit if the popups start getting in the way
* New implementations of `Window.Disable()` and `Window.Enable()`
* Previously did not work correctly at all
* Now using the "-disabled" attribute
* Allow Comboboxes to have empty starting values
* Was crashing
* Enables application to fill these in later
# 4.0.0 PySimpleGUI & 2.0.0 PySimpleGUI27 19-June-2019
* DOC STRINGS DOCS STRINGS DOC STRINGS!
* Your IDE is about to become very happy
* All Elements have actual documentation in the call signature
* The Readme and ReadTheDocs will be generated going forward using the CODE
* HUGE Thanks for @nngogol for both copying & adding all those strings, but also for making an entire document creation system.
* New __version__ string for PySimpleGUI.py
* New parameter to ALL `SetFocus` calls.
* def SetFocus(self, force=False)
* If force is True, then a call to `focus_force` is made instead of `focus_set`
* Get - New Radio Button Method. Returns True is the Radio Button is set
* Rename of Debugger class to _Debugger so IDEs don't get confused
* User read access to last Button Color set now available via property `Button.ButtonColor`
* Rename of a number of callback handlers to start with _
* Fix for memory leak in Read call. Every call to read lost a little memory due to root.protocol calls
* Listbox.Update - New parameter - scroll_to_index - scroll view so that index is shown at the top
* First PyPI release to use new documentation!
### Upcoming
Make suggestions people! Future release features
## Code Condition
Make it run
Make it right
Make it fast
It's a recipe for success if done right. PySimpleGUI has completed the "Make it run" phase. It's far from "right" in many ways. These are being worked on. The module is particularly poor for PEP 8 compliance. It was a learning exercise that turned into a somewhat complete GUI solution for lightweight problems.
While the internals to PySimpleGUI are a tad sketchy, the public interfaces into the SDK are more strictly defined and comply with PEP 8 for the most part.
Please log bugs and suggestions in the GitHub! It will only make the code stronger and better in the end, a good thing for us all, right?
## Design
A moment about the design-spirit of `PySimpleGUI`. From the beginning, this package was meant to take advantage of Python's capabilities with the goal of programming ease.
**Single File**
While not the best programming practice, the implementation resulted in a single file solution. Only one file is needed, PySimpleGUI.py. You can post this file, email it, and easily import it using one statement.
**Functions as objects**
In Python, functions behave just like object. When you're placing a Text Element into your form, you may be sometimes calling a function and other times declaring an object. If you use the word Text, then you're getting an object. If you're using `Txt`, then you're calling a function that returns a `Text` object.
**Lists**
It seemed quite natural to use Python's powerful list constructs when possible. The form is specified as a series of lists. Each "row" of the GUI is represented as a list of Elements. When the form read returns the results to the user, all of the results are presented as a single list. This makes reading a form's values super-simple to do in a single line of Python code.
**Dictionaries**
Want to view your form's results as a dictionary instead of a list... no problem, just use the `key` keyword on your elements. For complex forms with a lot of values that need to be changed frequently, this is by far the best way of consuming the results.
You can also look up elements using their keys. This is an excellent way to update elements in reaction to another element. Call `form.FindElement(key)` to get the Element.
**Named / Optional Parameters**
This is a language feature that is featured **heavily** in all of the API calls, both functions and classes. Elements are configured, in-place, by setting one or more optional parameters. For example, a Text element's color is chosen by setting the optional `text_color` parameter.
**tkinter**
tkinter is the "official" GUI that Python supports. It runs on Windows, Linux, and Mac. It was chosen as the first target GUI framework due to its ***ubiquity***. Nearly all Python installations, with the exception of Ubuntu Linux, come pre-loaded with tkinter. It is the "simplest" of the GUI frameworks to get up an running (among Qt, WxPython, Kivy, etc).
From the start of the PSG project, tkinter was not meant to be the only underlying GUI framework for PySimpleGUI. It is merely a starting point. All journeys begin with one step forward and choosing tkinter was the first of many steps for PySimpleGUI. Now there are 4 ports up and running - tkinter, WxPython, Qt and Remi (web support)
## Author
Mike - who wrote PySimpleGUI is not important. It's the software that's important
## License
GNU Lesser General Public License (LGPL 3) +
## Acknowledgments
#### SORRY!! Will add these back. Lost due to file length limitation

View File

@ -0,0 +1,19 @@
import inspect
import PySimpleGUI as sg
psg_members = inspect.getmembers(PySimpleGUI)
psg_funcs = [o for o in psg_members if inspect.isfunction(o[1])]
psg_classes = [o for o in psg_members if inspect.isclass(o[1])]
psg_classes_ = list(set([i[1] for i in psg_classes])) # filtering
psg_classes = list(zip([i.__name__ for i in psg_classes_], psg_classes_))
for i in psg_funcs:
if 'Tk' in i[0] or 'TK' in i[0] or 'Element' == i[0]: # or 'Window' == i[0]:
continue
print('')
print(f'<!-- <+func.{i[0]}+> -->')
# print('\n'.join(['\t' + j[0] for j in inspect.getmembers(i[1]) if '_' not in j[0] ]))
sg.Popup()
sg.Button()

View File

@ -0,0 +1,662 @@
from inspect import getmembers, isfunction, isclass, getsource, signature, _empty
from datetime import datetime
import PySimpleGUIlib
import click
import logging
import json
import re
import os
TAB_char = ' '
TABLE_TEMPLATE='''
Parameter Descriptions:
|Name|Meaning|
|---|---|
{md_table}
{md_return}
'''
TABLE_ROW_TEMPLATE = '|{name}|{desc}|'
TABLE_RETURN_TEMPLATE = '|||\n| **return** | {return_guy} |'
TABLE_Only_table_RETURN_TEMPLATE = '''|Name|Meaning|\n|---|---|\n| **return** | $ |'''
from collections import namedtuple
special_case = namedtuple('special_case', 'ok sig table just_text'.split(' '))
"""
injection_points:
injection_point structure cal look like this:
FUNCTION
{
"tag" : "<!-- <+func.hello+> -->",
"function_object" : "<function hello at 0x7fdcfd888ea0>",
"parent_class" : None,
"part1" : "func",
"part2" : "hello",
"number" : ""
}
{
"tag" : "<!-- <+func.1hello+> -->",
"function_object" : "<function hello at 0x7fdcfd888ea0>",
"parent_class" : None,
"part1" : "func",
"part2" : "hello",
"number" : "1"
}
CLASS
{
"tag" : "<!-- <+Mike_Like.__init__+> -->",
"function_object" : <function Mike_Like.__init__ at 0x7fdcfd888ea0>,
"parent_class" : <class '__main__.Mike_Like'>,
"part1" : "Mike_Like",
"part2" : "__init__",
"number" : ""
}
{
"tag" : "<!-- <+Mike_Like.2__init__+> -->",
"function_object" : <function Mike_Like.__init__ at 0x7fdcfd888ea0>,
"parent_class" : <class '__main__.Mike_Like'>,
"part1" : "Mike_Like",
"part2" : "__init__",
"number" : "2"
}
"""
def get_params_part(code: str) -> dict:
"""
Find ":param " part in given "doc string".
from __doc__ to {
'parameter' : 'desctiption',
'parameter2' : 'desctiption2',
'parameter3' : 'desctiption3',
}
"""
code = code.strip()
# if doc_string is empty
if code == None: return {}
elif '' == code.strip(): return {}
elif ':param' not in code: return {}
elif ':return' in code: # strip ':return:'
new_code = code[:code.index(':return:')]
regg_ = re.compile(r':return[\d\D]*?:param', flags=re.MULTILINE)
if len(list(regg_.finditer(new_code))) > 0:
if versbose:
print(f'warning-> ":return" MUST BY AT THE END. FIX IT NOW in {name_}!!!\nBut i will try to parse it...')
code = re.sub(regg_, r':param', code)
else:
code = new_code
try:
only_params = code[code.index(':param'):] # get_only_params_string(code)
except Exception as e:
if versbose: print(f'SORRY, fail at parsing that stuff in {name_}')
return {}
# making dict
param_lines = only_params.split(':param ')
param_lines = [re.sub(r'[ ]{2,}', ' ', i.strip(' ').strip('\t').replace('\n', ' '), flags=re.MULTILINE)
for i in param_lines if i.strip()] # filter empty lines
args_kwargs_pairs = {}
for index, i in enumerate(param_lines):
cols = i.split(':')
param_name, els = cols[0], '\n'.join(
[j.strip() for j in ':'.join(cols[1:]).split('\n')])
# param_name, els = cols[0], ' '.join([j.strip() for j in ':'.join(cols).split('\n')]) # can be this:
param_name, els = param_name.strip(), els.strip()
args_kwargs_pairs[param_name] = els
return args_kwargs_pairs
def get_return_part(code: str, line_break=None) -> str:
""" Find ":return:" part in given "doc string"."""
if not line_break:
line_break = ' <br> '
if ':return:' not in code:
return ''
return code[code.index(':return:')+len(':return:'):].strip().replace('\n', line_break)
def special_cases(function_name, sig, doc_string, line_break=None):
doca, params_names = doc_string.strip(), list(dict(sig).keys())
if 'self' in params_names and len(params_names) == 1 and not doca:
"""
def Get(self):
''' '''
->
```python
Get()
```
"""
return special_case(ok=True, just_text=f'\n\n```python\n{function_name}()\n```\n\n', sig='', table='')
# -return -param
elif 'self' in params_names and len(params_names) == 1 and doca and ':param' not in doca and ':return:' not in doca:
"""
def Get(self):
'''
blah blah blah
'''
->
```python
Get() # blah blah blah
```
"""
return special_case(ok=True, just_text=f'\n\n{doca}\n\n```python\n{function_name}()\n```\n\n', sig='', table='')
# +return -param
elif 'self' in params_names and len(params_names) == 1 and doca and ':param' not in doca and ':return:' in doca:
"""
def Get(self):
'''
blah blah blah
:return: blah-blah
'''
->
```python
Get()
```
*table*
"""
return_part, desc = get_return_part(doca, line_break=line_break), get_doc_desc(doca)
return special_case(ok=True, just_text='',
sig=f'\n\n{desc}\n\n`{function_name}()`\n\n',
table=TABLE_Only_table_RETURN_TEMPLATE.replace('$', return_part) + '\n\n')
# +return -param
elif 'self' in params_names and len(params_names) == 1 and doca and ':param' not in doca and ':return:' in doca:
"""
def SetFocus(self, elem):
'''
blah blah blah
:param elem: qwerty
'''
"""
return special_case(ok=False, just_text='', sig='', table='')
return special_case(ok=False, just_text='', sig='', table='')
def get_doc_desc(doc_string):
if ':param' in doc_string: doc_string = doc_string[:doc_string.index(':param')]
if ':return:' in doc_string: doc_string = doc_string[:doc_string.index(':return:')]
if ':param' in doc_string: doc_string = doc_string[:doc_string.index(':param')]
if ':return:' in doc_string: doc_string = doc_string[:doc_string.index(':return:')]
desc = doc_string.strip().replace(' ', '')
return f'\n{desc}' if desc else ''
def get_sig_table_parts(function_obj, function_name, doc_string, logger=None, is_method=False, line_break=None, insert_md_section_for__class_methods=False):
"""
Convert "function + __doc__" tp "method call + params table" in MARKDOWN
"""
doc_string = doc_string.strip()
# qpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqp
# 0 0 Making INIT_CALL 0 0 #
# qpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqp
try:
sig, rows = signature(function_obj).parameters, []
except Exception as e:
if logger: logger.error(f'PROBLEM WITH "{function_obj}" "{function_name}":\nit\'s signature is BS. Ok, I will just return \'\' for \'signature\' and \'param_table\'\nOR BETTER - delete it from the 2_readme.md.\n======')
return '', ''
for index, key in enumerate(sig):
val = sig[key].default
if 'self' == str(key):
continue
if val == _empty: rows.append(key)
elif val == None: rows.append(f'{key}=None')
elif type(val) is int: rows.append(f'{key}={val}')
elif type(val) is str: rows.append(f'{key}="{val}"')
elif type(val) is tuple: rows.append(f'{key}={val}')
elif type(val) is bool: rows.append(f'{key}={val}')
else:
raise Exception(f'IDK this type -> {key, val}')
sig_content = f',\n{TAB_char}'.join(rows) if len(rows) > 2 else f', '.join(rows)
# # # make 2 line signature into 1-line
# # # sig_content = f',\n{TAB_char}'.join(rows)
# # # if sig_content.count('\n') < 3: sig_content = re.sub(r'\n[ \t]{,8}', ' ', sig_content, flags=re.MULTILINE)
sign = "\n\n{0}\n\n```\n{1}({2})\n```".format(get_doc_desc(doc_string), function_name, sig_content)
if is_method:
if insert_md_section_for__class_methods:
sign = "#### {1}\n\n{0}\n\n```\n{1}({2})\n```".format(get_doc_desc(doc_string), function_name, sig_content)
else:
sign = "{0}\n\n```\n{1}({2})\n```".format(get_doc_desc(doc_string), function_name, sig_content)
# --------------
# SPECIAL CASES
# --------------
result = special_cases(function_name, sig, doc_string, line_break=line_break)
if result.ok:
if result.just_text:
return result.just_text, ''
else:
return result.sig, result.table
# qpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqp
# 0 0 Making params_TABLE 0 0 #
# qpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqpqp
# 1
return_guy = get_return_part(doc_string, line_break=line_break)
if not return_guy:
md_return = return_guy = ''
else:
return_guy = return_guy.strip()
md_return = TABLE_RETURN_TEMPLATE.format(return_guy=return_guy)
# return_guy = f'\n\nreturn value: {return_guy}\n'
# return_guy_val_str = return_guy
# 2
md_table = '\n'.join([TABLE_ROW_TEMPLATE.format(name=name, desc=desc)
for name, desc in
get_params_part(doc_string).items()])
# 3
params_TABLE = TABLE_TEMPLATE.format(md_table=md_table, md_return=md_return).replace(TAB_char, '').replace(' ', '').replace('\t', '')
# 1 and N
# if len(get_params_part(doc_string).items()) == 1:
# params_TABLE = TABLE_TEMPLATE.replace('Parameters Descriptions:', 'Parameter Description:').format(md_table=md_table, md_return=md_return).replace(TAB_char, '').replace(' ', '').replace('\t', '')
# else:
# params_TABLE = TABLE_TEMPLATE.format(md_table=md_table, md_return=md_return).replace(TAB_char, '').replace(' ', '').replace('\t', '')
if not md_table.strip():
params_TABLE = ''
if return_guy:
sign = sign[:-4] + f' -> {return_guy}\n```\n'
return sign, params_TABLE
def pad_n(text): return f'\n{text}\n'
def render(injection, logger=None, line_break=None, insert_md_section_for__class_methods=False):
if injection['part1'] == 'func': # function
sig, table = get_sig_table_parts(function_obj=injection['function_object'],
function_name=injection['part2'],
insert_md_section_for__class_methods=insert_md_section_for__class_methods,
doc_string=injection['function_object'].__doc__, logger=logger, line_break=line_break)
else: # class method
function_name = injection['parent_class'].__name__ if injection['part2'] == '__init__' else injection['part2']
sig, table = get_sig_table_parts(function_obj=injection['function_object'],
function_name=function_name, is_method=True,
insert_md_section_for__class_methods=insert_md_section_for__class_methods,
doc_string=injection['function_object'].__doc__, logger=logger, line_break=line_break)
if injection['number'] == '':
return pad_n(sig) + pad_n(table)
elif injection['number'] == '1':
return pad_n(sig)
elif injection['number'] == '2':
return pad_n(table)
else:
if logger: logger.error(f'Error in processing {injection}')
def readfile(fname):
with open(fname, 'r', encoding='utf-8') as ff:
return ff.read()
def main(do_full_readme=False, files_to_include: list = [], logger=None, output_name=None, delete_html_comments=True, delete_x3_newlines=True, allow_multiple_tags=True, line_break=None, insert_md_section_for__class_methods=True, remove_repeated_sections_classmethods=False):
"""
Goal is:
1) load 1_.md 2_.md 3_.md 4_.md
2) get memes - classes and functions in PSG
3) find all tags in 2_
4) structure tags and REAL objects
5) replaces classes, functions.
6) join 1 big readme file
:param do_full_readme: if False - use only 2_readme.md
:param files_to_include: list of markdown files to include in output markdown
:param logger: logger object from logging module
:param delete_html_comments: flag for preprocessing input markwon text e.g. deleting every html tag, that is injection_point
:param allow_multiple_tags: flag for replacing every tag in "input markdown text"
:param delete_x3_newlines: flag for deleting '\\n\\n\\n' in final output makrdown text
:param output_name: base filename of output markdown file
:param line_break: linebreak_character in "return part"
"""
if logger: logger.info(f'STARTING')
# 888888888888888888888888888888888888888888
# =========== 1 loading files =========== #
# 888888888888888888888888888888888888888888
HEADER_top_part = readfile('1_HEADER_top_part.md') # 1
readme = readfile('2_readme.md') # 2
FOOTER = readfile('3_FOOTER.md') # 3
Release_notes = readfile('4_Release_notes.md') # 4
# 8888888888888888888888888888888888888888888888888888888888888888888888888
# =========== 2 GET classes, funcions, varialbe a.k.a. memes =========== #
# 8888888888888888888888888888888888888888888888888888888888888888888888888
psg_members = getmembers(PySimpleGUIlib)
psg_funcs = [o for o in psg_members if isfunction(o[1])]
psg_classes = [o for o in psg_members if isclass(o[1])]
psg_classes_ = list(set([i[1] for i in psg_classes])) # filtering
psg_classes = list(zip([i.__name__ for i in psg_classes_], psg_classes_))
# IlilIlilIlilIlilIlilIlilIlilIlilIlilIlIlIl
# ilIli- | | -ilIli
# ilIli- _ __ ___ ___ __ _| |_ -ilIli
# ilIli- | '_ ` _ \ / _ \/ _` | __| -ilIli
# ilIli- | | | | | | __/ (_| | |_ -ilIli
# ilIli- |_| |_| |_|\___|\__,_|\__| -ilIli
# 8888888888888888888888888888888888888888888888888888888
# =========== 3 find all tags in 2_readme =========== #
# 8888888888888888888888888888888888888888888888888888888
# strip top of the file head
started_mark = '<!-- Start from here -->'
if started_mark in readme:
readme = readme[readme.index(started_mark)+len(started_mark):]
# find with regex
regex_pattern = re.compile(r'<!-- <\+[a-zA-Z_]+[\d\w_]*\.([a-zA-Z_]+[\d\w_]*)\+> -->')
mark_points = [i for i in readme.split('\n') if regex_pattern.match(i)]
# if there are REPEATED tags -> show them.
# if not allow_multiple_tags and len(list(set(mark_points))) != len(mark_points):
# [mark_points.remove(x) for x in set(mark_points)]
# if logger:
# logger.error("You have repeated tags! \n {0}".format(
# ','.join(mark_points)))
# return ''
# 8888888888888888888888888888888888888888888888888888888888888
# =========== 4 structure tags and REAL objects =========== #
# 8888888888888888888888888888888888888888888888888888888888888
injection_points = []
classes_method_tags = [j for j in mark_points if 'func.' not in j]
func_tags = [j for j in mark_points if 'func.' in j]
# 0===0 functions 0===0
for tag in func_tags:
try:
__, function_name = tag.split('.')
function_name = function_name.split('+')[0]
part2 = function_name
# {{{{{{{{{ filter number }}}}}}}}}
number = ''
if part2[0] in ['1', '2']:
number, part2 = part2[0], part2[1:]
# {{{{{{{{{ find function }}}}}}}}}
founded_function = [func for func_name,
func in psg_funcs if func_name == function_name]
if not founded_function:
if logger: logger.error(f'function "{function_name}" not found in PySimpleGUI')
continue
if len(founded_function) > 1:
if logger: logger.error(f'more than 1 function named "{function_name}" found in PySimpleGUI')
continue
# {{{{{{{{{ collect }}}}}}}}}
injection_points.append({
"tag": tag,
"function_object": founded_function[0],
"parent_class": None,
"part1": 'func',
"part2": part2,
"number": number,
})
except Exception as e:
if logger:
logger.error(f' {str(e)}')
continue
# 0===0 classes 0===0
for tag in classes_method_tags:
try:
class_name, method_name = tag.split('.')
class_name, method_name = class_name.split('+')[-1], method_name.split('+')[0]
part1, part2 = class_name, method_name
# {{{{{{{{{ filter number }}}}}}}}}
number = ''
if part2[0] in ['1', '2']:
number, method_name = part2[0], part2[1:]
# {{{{{{{{{ find class }}}}}}}}}
founded_class = [a_class_obj for a_class_name,
a_class_obj in psg_classes if a_class_name == class_name]
if not founded_class:
if logger: logger.error(f'class "{tag}" not found in PySimpleGUI')
continue
if len(founded_class) > 1:
if logger: logger.error(f'more than 1 class named "{tag}" found in PySimpleGUI')
continue
# {{{{{{{{{ find method }}}}}}}}}
try:
if method_name != 'doc':
founded_method = getattr(founded_class[0], method_name)
# GLG.append([founded_method, founded_class[0], method_name])
# string_type = str(type(founded_method))
# if 'property' in string_type or 'bound' in string_type:
# print(string_type)
# # import pdb; pdb.set_trace();
# if logger:
# logger.error(f'Property "{founded_method}" is not parsed.')
# continue
else:
founded_method = None
except AttributeError as e:
if logger: logger.error(f'METHOD not found!: {str(e)}')
continue
except Exception as e:
if logger: logger.error(str(e))
continue
# {{{{{{{{{ collect }}}}}}}}}
injection_points.append({
"tag": tag,
"function_object": founded_method,
"parent_class": founded_class[0],
"part1": part1,
"part2": part2,
"number": number,
})
except Exception as e:
if logger:
logger.error(f'```````````````````````{str(e)}')
continue
# 888888888888888888888888888888888888888
# =========== 5 injecting =========== #
# 888888888888888888888888888888888888888
success_tags = []
bad_tags = []
for injection in injection_points:
if injection['part2'] == 'doc': # our special snowflake "doc"
readme = readme.replace(injection['tag'], injection['parent_class'].__doc__)
else:
tag = injection['tag']
content = render(injection, logger=logger, line_break=line_break, insert_md_section_for__class_methods=insert_md_section_for__class_methods,)
if content:
success_tags.append(f'{tag} - COMPLETE')
else:
bad_tags.append(f'{tag} - FAIL')
readme = readme.replace(injection['tag'], content)
if logger:
success_tags_str = '\n'.join(success_tags).strip()
bad_tags_str = '\n'.join(bad_tags).strip()
good_message = f'DONE {len(success_tags)} TAGS:\n' + '\n'.join(success_tags) if success_tags_str else 'All tags are wrong//'
bad_message = f'FAIL WITH {len(bad_tags)} TAGS:\n' + '\n'.join(bad_tags) if bad_tags_str else 'No bad tags, YES!'
logger.info(good_message)
logger.info(bad_message)
# 8888888888888888888888888888888888
# =========== 6 join =========== #
# 8888888888888888888888888888888888
files = []
if 0 in files_to_include: files.append(HEADER_top_part)
if 1 in files_to_include: files.append(readme)
if 2 in files_to_include: files.append(FOOTER)
if 3 in files_to_include: files.append(Release_notes)
Joined_MARKDOWN = '\n\n'.join(files) if do_full_readme or files else readme
if output_name:
with open(output_name, 'w', encoding='utf-8') as ff:
curr_dt = datetime.today().strftime('<!-- CREATED: %Y-%m-%d %H.%M.%S -->\n')
content = curr_dt + Joined_MARKDOWN
# {{{{{{{{{ html removing }}}}}}}}}
if delete_html_comments:
if logger: logger.info('Deleting html comments')
# remove html comments
filt_readme = re.sub(
r'<!--([\s\S]*?)-->', '\n', content, flags=re.MULTILINE)
for i in range(5):
filt_readme = filt_readme.replace('\n\n\n', '\n\n')
# add staked_edit
if '<!--stackedit_data:' in content:
stackedit_data = content[content.index(
'<!--stackedit_data:'):]
filt_readme += stackedit_data
content = filt_readme
# {{{{{{{{{ filter multiple multilines EVERYWHERE }}}}}}}}}
if delete_x3_newlines:
# removing spaces
content = re.sub(r'^[ ]+$', '', content, flags=re.MULTILINE)
# removing \n
content = re.sub(r'\n{3,}', '\n\n',
content, flags=re.MULTILINE)
# {{{{{{{{{ remove repeated sections classmethods }}}}}}}}}
if remove_repeated_sections_classmethods:
rega = re.compile(r'((\#+\s\w+)\n\s){2}', flags=re.MULTILINE)
for index, i in enumerate(re.finditer(rega, content)):
print(f'{index} - > {i.group(0)}')
print(f'{index} - > {i.group(1)}')
content = content.replace(i.group(0), i.group(1))
# re
# content = re.sub(rega, r'\1', content, flags=re.MULTILINE)
# FINISH
content = content.strip()
ff.write(content)
if logger: logger.info(f'ending. writing to a file///////////////')
return content
if logger: logger.error(f'Error in main')
@click.command()
@click.option('-nol', '--no_log', is_flag=True, help='Disable log')
@click.option('-rml', '--delete_log', is_flag=True, help='Delete log file after generating')
@click.option('-rmh', '--delete_html_comments', is_flag=True, help='Delete html comment in the generated .md file')
@click.option('-o', '--output_name', default='FINALreadme.md', type=click.Path(), help='Name for generated .md file')
@click.option('-lo', '--log_file', default='LOGS.log', type=click.Path(), help='Name for log file')
def cli(no_log, delete_log, delete_html_comments, output_name, log_file):
# --------------------
# ----- logging setup-
# --------------------
logger = logging.getLogger(__name__)
if no_log:
logger.setLevel(logging.CRITICAL)
# delete_log = True
else:
logger.setLevel(logging.DEBUG)
my_file = logging.FileHandler(log_file, mode='w')
my_file.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s>%(levelname)s: %(message)s')
my_file.setFormatter(formatter)
logger.addHandler(my_file)
main(logger=logger,
files_to_include=[0, 1, 2, 3],
output_name=output_name,
delete_html_comments=delete_html_comments)
# --------------------
# ----- POST process--
# --------------------
if delete_log:
# delete log file
log_file = os.path.join(os.path.dirname(
os.path.abspath(__file__)), log_file)
if os.path.exists(log_file):
try:
os.remove(log_file)
except Exception as e:
logger.error(str(e))
if __name__ == '__main__':
# my_mode = 'cli-mode'
# my_mode = 'debug-mode'
my_mode = 'debug-mode2'
if my_mode == 'cli-mode':
cli()
elif my_mode == 'debug-mode':
main(files_to_include=[0, 1, 2, 3],
output_name='johnson_n_johnson.txt',
delete_html_comments=True)
elif my_mode == 'debug-mode2':
import logging; logger = logging.getLogger(__name__); logger.setLevel(logging.DEBUG)
my_file = logging.FileHandler('usage.log.txt', mode='w'); my_file.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s>%(levelname)s: %(message)s')
my_file.setFormatter(formatter); logger.addHandler(my_file);
main(logger=logger, files_to_include=[1],
output_name='johnson_n_johnson.txt',
delete_html_comments=True)

96
readme_creator/run_me.py Normal file
View File

@ -0,0 +1,96 @@
from make_real_readme import main
########################################################################
# __ _ _ #
# / _(_) | | #
# __ __ ___ ___ _ __ | |_ _ __ _ | |__ ___ _ __ ___ #
# \ \ / / / __/ _ \| '_ \| _| |/ _` | | '_ \ / _ \ '__/ _ \ #
# \ V / | (_| (_) | | | | | | | (_| | | | | | __/ | | __/ #
# \_/ \___\___/|_| |_|_| |_|\__, | |_| |_|\___|_| \___| #
# __/ | #
# |___/ #
########################################################################
OUTPUT_FILENAME = 'readme.md'
##-#-#-# ##-#-#-#
# Pre-process logic
##-#-#-# ##-#-#-#
line_break = '<br>'
# line_break can be:
# - '<br>'
# - ' \n '
method = 'with logs'
# method can be:
# - 'simple, no log'
# - 'with logs'
##-#-#-# ##-#-#-#
# Post-process logic
##-#-#-# ##-#-#-#
enable_popup = True
insert_md_section_for__class_methods = False
remove_repeated_sections_classmethods = False
##############
# __ #
# /_ | #
# | | #
# | | #
# | | #
# |_| #
##############
if method == 'simple, no log':
main(logger=None,
insert_md_section_for__class_methods=insert_md_section_for__class_methods,
remove_repeated_sections_classmethods=remove_repeated_sections_classmethods,
files_to_include=[0, 1, 2, 3],
output_name=OUTPUT_FILENAME,
delete_html_comments=True)
################
# ___ #
# |__ \ #
# ) | #
# / / #
# / /_ #
# |____| #
################
if method == 'with logs':
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
my_file = logging.FileHandler('usage.log.txt', mode='w')
my_file.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s>%(levelname)s: %(message)s')
my_file.setFormatter(formatter)
logger.addHandler(my_file)
logger.info('STARTING')
main(logger=logger,
insert_md_section_for__class_methods=insert_md_section_for__class_methods,
remove_repeated_sections_classmethods=remove_repeated_sections_classmethods,
files_to_include=[0, 1, 2, 3],
output_name=OUTPUT_FILENAME,
delete_html_comments=True)
########################################
# _____ #
# | __ \ #
# | |__) |__ _ __ _ _ _ __ #
# | ___/ _ \| '_ \| | | | '_ \ #
# | | | (_) | |_) | |_| | |_) | #
# |_| \___/| .__/ \__,_| .__/ #
# | | | | #
# |_| |_| #
########################################
if enable_popup:
import PySimpleGUI as sg
sg.Popup('Completed making {}'.format(OUTPUT_FILENAME))

View File

@ -0,0 +1,37 @@
import inspect
import PySimpleGUIlib
"""
Create All Possible Tags
Will output to STDOUT all of the different tags for classes, members and functions for a given PySimpleGUIlib.py
file. Functions that begin with _ are filtered out from the list.
Displays the results in a PySimpleGUI window which can be used to copy and paste into other places.
"""
layout = [[PySimpleGUIlib.Output(size=(80,20))]]
window = PySimpleGUIlib.Window('Dump of tags', layout, resizable=True).Finalize()
psg_members = inspect.getmembers(PySimpleGUIlib)
psg_funcs = [o for o in psg_members if inspect.isfunction(o[1])]
psg_classes = [o for o in psg_members if inspect.isclass(o[1])]
# I don't know how this magic filtering works, I just know it works. "Private" stuff (begins with _) are somehow
# excluded from the list with the following 2 lines of code. Very nicely done Kol-ee-ya!
psg_classes_ = list(set([i[1] for i in psg_classes])) # filtering of anything that starts with _ (methods, classes, etc)
psg_classes = list(zip([i.__name__ for i in psg_classes_], psg_classes_))
for i in psg_classes:
if 'Tk' in i[0] or 'TK' in i[0] or 'Element' == i[0]: # or 'Window' == i[0]:
continue
print('')
print(f'<!-- <+{i[0]}.doc+> -->')
print(f'<!-- <+{i[0]}.__init__+> -->')
print('\n'.join([f"#### {j[0]}\n\n<!-- <+{i[0]}.{j[0]}+> -->\n" for j in inspect.getmembers(i[1]) if '_' not in j[0] ]))
print('\n------------------------- Functions start here -------------------------\n')
for f in psg_funcs:
print(f"<!-- <+func.{f[0]}+> -->")
window.Read()