Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
Announcements - New Features, Design Patterns, and Methods
I'm unsure how GitHub sends out updates. I don't think people are informed about Wiki changes for example. I've been announcing new features and more importantly, new ways of doing things, on the Wiki. I'm going to put announcements here so they are more visible. If there are objections about the traffic, well, what can I say, it's a busy/active project.
New use pattern - Element lookup using Keys
To get an element object from a form, you call
This is the new, preferred method for doing Updates on elements.
Previously if you wanted to output something to a Text Element, you needed to create the text element outside of the form layout and keep that text element variable around so you can call
The new design pattern is thus:
Later in your code you can update this Text Element by making this call, assuming the variable form is your FlexForm object:
The Demo programs have all been updated to use this new technique. This capability and its impact on the length of programs led to pushing version 2.30 out the door quickly.
Borderless Windows are Here
Try them on your next form.
You can expect to see some of these in the Demo programs.
You can click anywhere on the window and drag to move it. Don't forget to put an exit key on these windows.
Be sure and make an "exit" button or you'll be running task manager to close your windows. The reason is the when you turn on this option, you will not see an icon on your taskbar for the window. This happens on both Windows and Linux. Thus, if you do not supply an exit button, the user will have no means to close the window.
Tonight's change is perhaps going to be a really cool thing or one that is going to piss people off.
But, hey, I like it this way. If you don't, set
As the name implies, you can grab and drag your window using any point on the window, not just the title bar. I was only enabling this when the title bar was turned off. I think it's a much superior way to interact with a window.
FlexForm is becoming quite the call!
So, enjoy a lazy way of interacting with windows on me.
You will want to turn if off for forms with a SLIDER. you need the slider to move, not the window. I'll update the Demos that use sliders to turn off the grab_anywhere.
This one has been requested a number of times. Rather than make a Table Element, decided to see if the current PySimpleGUI is capable of making nice tables using standard Elements. The answer seems to be yes, it's possible with existing Elements. The key was to enable text justification in the InputText element. By right justifying the text in those Elements, it's possible to create a nice looking table.
Here's an example using a ComboBox and Input Elements.
You'll find the code that generated the table in the file Demo_Table_Simulation.py. It requires the latest PySimpleGUI from GitHub in order to use the justification setting.
This is a "live keyboard" demo. It updates the table values as you are typing.
There are 3 fields at the top of the table. If you enter a value into the 3rd field, the cell that the other 2 cells represents will be changed to that value. Enter 1, 2, 1234 and cell (1,2) will be changed to 1234.
There is a new trick demonstrated in this demo that shows off the power of Python. Rather than pass in a string as the key to the Input Elements, I passed a tuple. Nothing about the key requires it to be a string. The only requirement is that you use the same type to look up the element when you call FindElement or use the key to read the return values.
This is the code that makes the Input Elements:
See how the key is set to (i,j). This allow me to easily find the Element that is represented by (i,j) later. What to access the cell at (0,0)? This you would make this call:
Hopefully this is enough capability for the folks that need tables in their forms/window.
3.0.2 release today to turn off the grab_anywhere feature for non-blocking forms. tkinter is printing out a warning/error message when the form is closed using a button. Doesn't appear to have any effect on the overall functioning, but it's distressing to see. Better to disable this feature for now.
Plan is to add back an override mechanism should a user want it.
Floating Toolbar - New demo program
This is an always-on-top, compact floating toolbar. They are super-handy to leave running. Something satisfying about writing code that then gets used often, especially if they make you much more efficient.
Updated the Readme / primary doc to discuss the use of non-block forms.
As explained in the documentation there are a number of techniques to move away from async forms including using the
Floating Desktop Widgets
I've discovered that in about 30 lines of code you can create a floating desktop widget.
If you click the pause button, it switches to Run.
This "Widget" is always on top of the other windows.
Looking for a way of launching these in a way that have no taskbar icons. If launched from PyCharm it behaves this way. If launched from a Toolbar, the toolbar's window is attached to the timer. Close it and the timer closes.
This demo is the first time I've ever combined a ReadNonBlocking with a Read in the same form. The reason for using it in this program is that while the timer is paused, there' s nothing happening so why have the program running the loop when it can wait for the user to do something like click a button. When the button is clicked we return from the Read call.
Thank you to jfong for sending an interesting version of this program. His ideas have rolled into a into the project code many times.
Menus! (and a Listbox.Update bug) are the big features.
Since the Menu code is somewhat isolated, and I want to get some users on it, decided to go ahead and push it all out there in 3.01.00
I didn't mention this in the readme section on menus, but by default (you can't currently turn it off) menus are detachable. If you double-click the dashed line then you get a floating version of that menu. Should make for some pretty interesting user interfaces?
Update methods updated
Added the ability to enable / disable all input elements.
A number of Demo programs also refreshed.
Expect a PyPI release soon.
Note that some Update method changes also changed parameter names from new_value to value, new_values to values. Some were different than others. Removed new_ so they all match now. Sorry to those living on the bleeding edge!
Here's a before/after. Elements towards the bottom of the window were disabled.
Yes, even buttons can be disabled now. No more needing to gray out your own buttons!
Big change this time around is the ability to disable widgets. All input widgets have an Update method that has the parameter
A few critical bugs in there too which pushed up the release to today.
Resizable Windows, Font settings for input text elements, beginnings of Treeview Element
You can stretch windows bigger now and some of the elements will resize with the window. **
The Input Text Elements did not have a functioning Font setting. Doh! Don't know how that got missed.
The very beginnings of the Treeview element are in there.
Hopefully nothing was broke. Any time I make changes to the core widget packing I get nervous!
** Had to turn off some of the Resizable windows features....Buttons and other elements were moving / expanding in forms that I didn't want the to expand. The change fucked up too many elements to leave on for now.
Two new Demo programs - CPU Desktop Widget, Spinner Compound Element
Added another Desktop Widget to the demos. This one shows the CPU utilization.
The spinner allows you to change how often it's refreshed
The Spinner Compound Element was done in response from a user wanting to see a different kind of spinner. This one has larger buttons and is laid out horizontally.
The point of this demo is that it's possible to put together multiple Elements into a higher level element. There aren't many of these I can think of at the moment, but given how many user questions are asked, something else is bound to be asked for.
Table Element, Complete rework of Popups, Death of MsgBox
You can blame the Popup changes on this issue:
All of the Popups were rewritten to use a long list of customization parameters. The base Popup function remained more or less the same.
Decided while I was going all the Popup work that it's time to completely remove MsgBox. Sorry all you early adopters. You'll need to do a bulk rename and then you'll be fine.
Finally have something to show in the form of tables. The element name is
A Demo program is in the works.
It's possible to add scrollbars to the Table element by simply placing it into a Column element.
There's still work to do and a good number of bugs, but I encourage you to give it a try.
If you do not put the Table Element inside of a Column, then you can still view and scroll the table, it just will not have scrollbars.
There is a problem currently with keyboard input when placed into a Column. The keyboard keys work fine when NOT inside of the Column but stop working when placed inside a Column Element.
This program will read a CSV file and display it in a window.
It's another bit of PySimpleGUI "challenge code"..... The challenge is to do the same operation in another GUI framework in less lines of code. I would enjoy seeing the tkinter code required to create the window that this 20 line PySimpleGUI program creates. Most of the code deals with reading the CSV file
Linux Virtual Environment
I finally installed VirtualBox and am running Ubuntu Linux. I tried to install the Mint distro, but the display was scrambled when it booted.
I was surprised how close the Linux screen shots look to the Windows.
Even Pong worked the first time.
I don't believe that Python has been labelled the "go to language" for doing cross-platform GUI work. I guess I never stopped to think about it. I don't recall seeing this kind of thinking in posts or books I've read on Python. Perhaps it's time for that to change?
Released a new release to PyPI. Sorry about all these releases, but features continue to pour into the code. I'm finding even the folks that are actively using PySimpleGUI only run the pip installed version rather than the GitHub version. That means if I want runtime on the code, I'm only going to get any is to do a full release.
There were a number of changes that could f-up, so be on the lookout. The biggest addition to 3.2.0 was the Table Element (beta quality at the moment).
If you are running older programs then you may crash due to missing functions, MsgBox and several others. This is because I've moved 100% to Popup calls. It's not like I haven't been warning people so I don't expect complaints.
Some people are calling
Instead of calling
The call sequence becomes this:
You'll also find the Finalize call used in the scripts that use the Canvas Element.
See the Readme for more info on what's in the release. Note that the readme has not yet been updated with the Table Element and several other changes. There's only so much I can do.
One Line Progress Meters
PySimpleGUI has always had a one-line progress meter called EasyProgressMeter. However, that function has a limitation of only 1 meter being active at a time.
The new way to do Progress Meters is the function OneLineProgesssMeter.
All of the documentation and examples will reflect this new function.
Have to say it's nice to be able to run as many meters as desired without having to worry about more than 1 being on the screen at a time.
I intend to remove EasyProgressMeter within the next 5 or 6 releases to PyPI. I tried to insert a warning in the code, but too much code was shared to fit the message in.
I'm sorry about the change, but really would like to both add this function and rename the capability to something very descriptive. If there is enough revolt over removing EasyProgressMeter, I'll leave it in and simply drop it from all the documentation.
Yea, yea, it seems like only yesterday that version 3.2.0 was released. That's because it WAS only yesterday. I've been busy.
There are 2 changes I wanted out quickly....
The Progress Meter feature alone is a great use of PySimpleGUI. A number of users are using it only for this purpose in their programs.
New demo program - graph ping using canvas.
There is another ping-graph demo using Matplotlib. This graph only uses tkinter.
Finally, because the pings take a long time, I moved the ping calls outside of the GUI event loop. Calling ping inside event loop was causing the GUI to respond sluggishly. This is because the ping was taking 1 second which means the gui wasn't being refreshed / wasn't responsive during the second. Now the GUI sleeps for 200 ms while the ping is done by a thread.
This is yet another toe in the water with threading. The problems I saw in the past are no longer there, it would appear.
I also checked in the ping.py file that you need for this demo. It's a pure python implementation of ping and works pretty well, even if slow.
Thanks to @JorjMcKie I've learned more about the performance of the EasyProgressMeter and thus probably the OneLineProgressMeter. The more arguments to display the longer it takes.
Was going to document in the Cookbook / Readme that if you have performance concerns, you can call the progress meter less frequently. You don't have to update it 1 count at a time. It could be like this:
This meter is only called every 5 times through the loop. It finished quite a bit quicker than the test updating the meter every single time.
PySimpleGUI programs as an EXE file!
The biggest thing to hit PySimpleGUI since Colors.... the ability to run programs written for PySimpleGUI as an exe file. ALL credit goes to @JorjMcKie for this.
There is no need to distribute Python with your programs. It's all included in the exe and folder of supporting files.
From what I understand of nuitka, this code is compiled C++ code, not python code. The performance is thus potentially better! It's the best of both worlds.
Working to get the process documented. It's tricky and required a special script. Stay tuned....
This one is pretty exciting as it does something new on the screen. The Graph Element allows you to easily create a canvas and draw on it using your own coordinate system. You don't need to do conversions from your graph coordinates to the tkinter canvas graph coordinates.
The Demo program for it is a good example. It displays a pint graph. The graph we're creating is a line graph what we would like to to from 0,0 in the bottom left to 100, 500 in the upper right. This will give us 100 data points along the x axis and up to 500 ms on the y axis.
After creating the Graph Element, we can do 3 operations on it:
The draw line draws a line from 1 point to another. The points are specified using your graph coordinates, not the tkinter canvas coordinates.
I know I have a LOT of documentation to do.
In the meantime, try using Control+P if you're using PyCharm. Press Control+P while you are typing in the parameters and you'll see a popup showing you what the legal parameters are. This feature is almost necessary when using PySimpleGUI because functions have SO many optional parameters.
I hope to see some cool creations using the capability. I'm starting to see more and more projects pop up on GitHub that use PySimpleGUI! Keep those examples coming! And keep the requests for new features coming too. They have made this such a better package because of your help.
This is your layout:
To draw a line, call DrawLine:
More on docs....
Of course the best place to READ the docs is on ReadTheDocs (http://www.PySimpleGUI.org). There you'll get a nice table of contents down the left side. It's easier to navigate than the plain readme.
Last post showed an image of what happens when you put your cursor on a PySimpleGUI Element in your code. Let's see what happens when you do this with the other GUI packages.
Qt.... how about QRadioButton as an example:
hmmmm.... not much there... surely a button will have info...
Python 3.7.4 tkinter Is BROKEN - Not supported by PySimpleGUI
After much time spent by myself and multiple other parties, I've shown that the tkinter that's installed with Python 3.7.4 is broken. It does not display Table colors.
Python 3.7.2 does work and will be the highest level of Python 3.7 that PySimpleGUI will support for the time being. I'm not going to spend another minute debugging tkinter for the 3.7 team.
I'll add this to the readme / read the docs.
Sorry to all those that wasted time on this.
New features for tables
I completed the Table colors Update support for Tables in PySimpleGUI. You can set the text and background colors of tables using the
This particular feature and the massive addition of docstrings is inching us towards a 4.1 PySimpleGUI release.
Ability to set background color of Tooltips using PySimpleGUI
I have exposed the background color for tooltips. You can set the variable:
import PySimpleGUI as sg sg.TOOLTIP_BACKGROUND_COLOR = "#ffffe0"
The cruel GitHub Issue Searching Results
As you can see I use GitHJub Issues for a lots of things besides just issues. The reason is really simple, when searching GitHub Issues for a problem, I definitely want these "notes", announcements, suggestions, templates, screenshots,etc, to be searched as well.
WHAT!? Over 400 entries written are hidden. OK, so I manage to find this little box and I click it. What happens? Well, I see more, but then it's replaced with another little box
Oh, great, I'm "down to only'" 356 hidden entries". Search for "hidden entries", click again, searching, click, lather rinse repeat.
This happens for these Announcements as well as the screenshots.
I've tried to find ways of turning this off, but nothing has worked. So, it's time to break them apart so that all entries can be seen. It may take splitting into 3 or 4 or more Issues, but it's going to be worth it for sure as a lot of screenshots are hidden and a lot of good knowledge hidden as well.
Just updated the Issue that has the "Pull Request Policy" in it. I thought that since it's so short I'll just copy it here too.
TLDR - Not taking pull requests for core code. I'll still listen to your suggestions.
Pull Request Policy
I've talked about Pull Requests several times over the past year in the Announcements Issue. But, the way GitHub works, it hides a LOT of posts when you look at an Issue. The result is that even if you search for Pull in the Announcements Issue, you will not find the full set of posts.
Pull Requests - Not taking pull requests for core code
If you have a bug fix or suggestion for enhancement in the core code, I'm still interested in taking a peek, but I'm not doing direct merges.
Pull requests are already rare so I don't think it's going to affect much of anything.
There are a lot of reasons that I won't bother listing. Let's just sum it up as more efficient, much happier without them.
This first year has gone really well. I fully expect year 2 to be just as productive.
Still Have Something To Share?
Some users are submitting their "suggested code changes" as part of the Issue they are using to report a bug. I love these kinds of fixes and suggestions. I find them easier to digest and they don't feel like a bag of code has just been dropped into my lap that I must deal with.
This will rub a few the wrong way and for that I'm really sorry. Perhaps it's not in the spirit of Open Software to work in this manner but I hear from a lot more happy users right now than unhappy ones and so this really shouldn't have an impact.
Updated Readme/ReadTheDocs and Cookbook
I'm REALLY sorry to all the newcomers that hit example #1 in the readme, the example using the "Designer tool" (pencil and paper). The problem is that the
Instead of the pleasant 5 minute install and run, you likely had a 2 minute install process followed by a really large amount of time spent on trying to get the example to run. Sh*t! I'm really sorry about that.
Both the Cookbook and the main documentation have undergone a number of changes to both explain things better and removal of this kind of non-working crap! It all just got a little out of control there for a bit.
Slow Going - FINALLY cramming out a release for PySimpleGUI 4.1
Sorry that it's so slow the past few weeks. These docs have been a real chore and continue to. There has never been such a long time between releases.
I'm pulling together release notes now, but it's going to take a while as there are 616 changes since to the last PySimpleGUI release and each are checked before the release will go out.
PySimpleGUI 4.1 Anniversary Release! 4-Aug-2019
Long time coming. Docstrings continue to be a focus.
NOTE the Python 2 version is still in the works.
It's been a minute
The documentation beat goes on. It's what most all of the time is spent on, in addition to support.
There are features and fixes going into all ports. Today I think all ports except Wx got some code change to them.
There has been so much going on and yet so little at the same time. I think spreading outward in all directions is about the best way to describe it.
Column sizes work now in PySimpleGUI (on GitHub)
New documentation sections OTW include:
Thanks for all the inspiration folks!
Micro-Demos - Small programs that do something useful and can be pasted
Sorry for a lengthy post, but it does have 4 complete programs and 2 screen shots.
What makes these Micro-Demos fun is that they are short enough to "post" on a forum or GitHub Issue or on Reddit. No link to follow, just a short complete program. No code fragment to integrate either.
There have been a number of awesome features added / completed in PySimpleGUI (the main version). The reason PySimpleGUI tends to be more complete, mature is that it's the flagship of the family of ports. It's the proving ground as well for new SDK changes.
Demo 1A - Viewing a webcam in a GUI window using OpenCV - compacted
Modified existing demo to create a super-simplified, get the point through, demo. It's a whopping 13 lines of code if compacted:
import PySimpleGUI as sg import cv2 layout = [[sg.Image(filename='', key='image')],] window = sg.Window('Demo Application - OpenCV Integration', layout, location=(800,400)) cap = cv2.VideoCapture(0) while True: event, values = window.Read(timeout=20, timeout_key='timeout') if event in ('Exit', None): break ret, frame = cap.read() imgbytes=cv2.imencode('.png', frame).tobytes() window.FindElement('image').Update(data=imgbytes) window.Close()
Demo 1AA - Ultra Compact
This is just plain showing off. It's 7 lines in total. 8 if you add the CR to my if statement ;-)
import cv2, PySimpleGUI as sg window = sg.Window('Demo Application - OpenCV Integration', [[sg.Image(filename='', key='image')],], location=(800,400)) cap = cv2.VideoCapture(0) while True: event, values = window.Read(timeout=20, timeout_key='timeout') if event is None: break window.FindElement('image').Update(data=cv2.imencode('.png', cap.read()).tobytes())
But that's not very readable, so let's go back to the original for this one. It's "fancy". It doesn't have a titlebar for example. And, if you uncomment the line for the right click menu, you'll be able to exit the application if you're not running in an IDE.
Demo 1B - Viewing a webcam in a GUI window using OpenCV - commented
import PySimpleGUI as sg import cv2 def main(): sg.ChangeLookAndFeel('Black') # define the window layout layout = [[sg.Image(filename='', key='image')],] # create the window and show it without the plot window = sg.Window('Demo Application - OpenCV Integration', layout, location=(800,400), no_titlebar=True, grab_anywhere=True,) # right_click_menu=['&Right', ['E&xit']],) # ---===--- Event LOOP Read and display frames, operate the GUI --- # cap = cv2.VideoCapture(0) while True: event, values = window.Read(timeout=20, timeout_key='timeout') if event in ('Exit', None): break ret, frame = cap.read() imgbytes=cv2.imencode('.png', frame).tobytes() window.FindElement('image').Update(data=imgbytes) window.Close() main()
What is downright extraordinary is that no special code was put in PySimpleGUI to support OpenCV. This just naturally happens if you write the right code. The code only uses PySimpleGUI and OpenCV.
Finally, it works on PySimpleGUIQt and PySimpleGUIWeb, you guessed it... by changing the import statement. STUNNED is how I feel every time this works. BTW, the Web version flickers and is being worked by the Remi team now.
Demo 2 - Drawing On Top of An OpenCV Stream - Released as
'Combo', 'Tab', 'TabGroup' Changes - Import API calls deprecated
I'm really sorry if you implemented code using some recently released API changes.
It's rare to flat out break the PySimpleGUI API, but this is a "band-aid" moment. The changes were recent, the number of users that likely used the deleted methods are few. So, rather than slowly remove them over time, they just disappeared and were replaced by others that will give you the data you need.
Rules are meant to be broken, but not architectures. In this case, the "don't break the install base's code" rule is broken, but as explained, the size of the impact is relatively small, but I DO feel the pain of those that are impacted. I'm really sorry about this.
The problem was that I hastily made some changes to the code that don't fit the big-picture architecture of PySimpleGUI. Without boring you too much - basically I added some stuff that uses "indexes" and I named some methods in inconsistent ways or I didn't implement the right method.
ComboBox and TabGroup changes
There was a recent addition that returned the "Currently selected item" in terms of "index". This isn't how it's been done across all the ports for the other elements. The remedy is to supply methods that fit the architecture.
Another dumb but fun demo - realtime ASCII movie from your webcam
from PIL import Image import numpy as np import PySimpleGUI as sg; font_size=6 # import PySimpleGUIQt as sg; font_size=8 # if using, be sure and use the second layout that is commented out # import PySimpleGUIWeb as sg; font_size=12 # yes, it runs in a webpage too! import cv2 """ Interesting program that shows your webcam's image as ASCII text. Runs in realtime, producing a stream of images so that it is actually animated ASCII text. Wild stuff that came about from a post on Reddit of all places. The software bits that turn the image into ASCII text were shamelessly taken from this gist: https://gist.github.com/cdiener/10491632 Brilliant work to have pulled off so much with so little Numpy What's remarkable about this program is that the animation is created by updating individual Text Elements going down the window, one line at a time, every time through the loop. That's 48 lines of text every time. Rough timing shows an animation of more than 10 fps when running any of the PySimpleGUI ports. """ # The magic bits that make the ASCII stuff work shamelessly taken from https://gist.github.com/cdiener/10491632 chars = np.asarray(list(' .,:;irsXA253hMHGS#9B&@')) SC, GCF, WCF = .1, 1, 7/4 sg.ChangeLookAndFeel('Black') # make it look cool # define the window layout NUM_LINES = 48 # number of lines of text elements. Depends on cameras image size and the variable SC (scaller) layout = [*[[sg.T(i,size=(120,1), font=('Courier', font_size), key='_OUT_'+str(i))] for i in range(NUM_LINES)], [ sg.Button('Exit')]] # if using PySimpleGUIQt, use this layout instead. The text rows are too far apart otherwise. # layout = [*[[sg.T(i, size_px=(800,12), font=('Courier', font_size), key='_OUT_'+str(i))] for i in range(NUM_LINES)], # [ sg.Button('Exit')]] # create the window and show it without the plot window = sg.Window('Demo Application - OpenCV Integration', layout, location=(800,400), no_titlebar=True, grab_anywhere=True, element_padding=(0,0)) # ---===--- Event LOOP Read and display frames, operate the GUI --- # cap = cv2.VideoCapture(0) # Setup the OpenCV capture device (webcam) while True: event, values = window.Read(timeout=0) if event in ('Exit', None): break ret, frame = cap.read() # Read image from capture device (camera) img = Image.fromarray(frame) # create PIL image from frame # More magic that coverts the image to ascii S = (round(img.size * SC * WCF), round(img.size * SC)) img = np.sum(np.asarray(img.resize(S)), axis=2) img -= img.min() img = (1.0 - img / img.max()) ** GCF * (chars.size - 1) # "Draw" the image in the window, one line of text at a time! for i, r in enumerate(chars[img.astype(int)]): window.Element('_OUT_'+str(i)).Update("".join(r)) window.Close()
It's posted in the demo section as
THANK YOU FOR FILLING OUT THE ISSUE FORMS
Damn, we've got the best users ever here!
It's a pain in the ass to fill out an Issue form, answer the billion questions including perhaps an uncomfortable experience level one.
The experience level really helps make sure stuff is explained at a level you're likely able to easily digest. You've not going to be satisfied if a response goes way over your head and you'll be even more unsatisfied if the responses are well under your years of experience.
The experience question is not meant to embarrass or demean or any other nefarious purpose. It's an honest attempt to provide better support. Besides, you have nothing to be embarrassed about!! None of us was born with programming skills. It's a 100% learned skill and every person here had a very first day of using Python.
More ASCII movies
Did one more pass at this thing. Comments removed to save space.
Controls were added to the bottom. The latest GitHub made them larger for easier use, but's not shown in the movie.
Here's a movie showing what it's like to mess around with controls:
The ability to modify one or many parameters and see the result, in realtime, is where PySimpleGUI excels greatly over a command line only option. Just by clicking a spinbox or sliding a slider I can instantly see the effect it has.
Anywhere that "Tuning" is part of the process, a GUI can potentially greatly help. The model - [Running code, stopping, changing variable in code, running code again] cannot compete with click a button and instantly see the change. CLI vs GUI people, continue to debate this as long as you want.
This same kind of "parameter modification" was used in the YOLO demo. You can easily see how changing the "Threshold" has an impact on the classifier.
So, if you want to interact more with your program directly, consider exposing the knobs to turn in a GUI. With PySimpleGUIQt you could literally make them knobs
Here's the modified program that also removes the need to modify anything except the 3 lines at the top in order to move from one platform to another.
Finally, notice this program "Generates the Layout". This topic is being added to the docs.... how to "Build" a GUI layout using Python code. In this case, 48 lines of Text Elements were created in a single statement.
from PIL import Image import numpy as np import PySimpleGUI as sg; font_size=6; USING_QT=False # import PySimpleGUIQt as sg; font_size=8; USING_QT=True # if using, be sure and use the second layout that is commented out # import PySimpleGUIWeb as sg; font_size=12; USING_QT=False # yes, it runs in a webpage too! Not as good as tkinter but works import cv2 # The magic bits that make the ASCII stuff work shamelessly taken from https://gist.github.com/cdiener/10491632 chars = np.asarray(list(' .,:;irsXA253hMHGS#9B&@')) SC, GCF, WCF = .1, 1, 7/4 sg.ChangeLookAndFeel('Black') # make it look cool # define the window layout NUM_LINES = 48 # number of lines of text elements. Depends on cameras image size and the variable SC (scaller) if USING_QT: layout = [[sg.T(i, size_px=(800, 12), font=('Courier', font_size), key='_OUT_' + str(i))] for i in range(NUM_LINES)] else: layout = [[sg.T(i,size=(120,1), font=('Courier', font_size), pad=(0,0), key='_OUT_'+str(i))] for i in range(NUM_LINES)] layout += [[ sg.Button('Exit', size=(5,1)), sg.T('GCF', size=(4,1)), sg.Spin([round(i,2) for i in np.arange(0.1,20.0,0.1)], initial_value=1, key='_SPIN_GCF_', size=(5,1)), sg.T('WCF', size=(4,1)), sg.Slider((1,4), resolution=.05, default_value=1.75, orientation='h', key='_SLIDER_WCF_', size=(15,15))]] # create the window and show it without the plot window = sg.Window('Demo Application - OpenCV Integration', layout, location=(800,400), font='Any 18') # ---===--- Event LOOP Read and display frames, operate the GUI --- # cap = cv2.VideoCapture(0) # Setup the OpenCV capture device (webcam) while True: event, values = window.Read(timeout=0) if event in ('Exit', None): break ret, frame = cap.read() # Read image from capture device (camera) img = Image.fromarray(frame) # create PIL image from frame GCF = float(values['_SPIN_GCF_']) WCF = values['_SLIDER_WCF_'] # More magic that coverts the image to ascii S = (round(img.size * SC * WCF), round(img.size * SC)) img = np.sum(np.asarray(img.resize(S)), axis=2) img -= img.min() img = (1.0 - img / img.max()) ** GCF * (chars.size - 1) # "Draw" the image in the window, one line of text at a time! for i, r in enumerate(chars[img.astype(int)]): window.Element('_OUT_'+str(i)).Update("".join(r)) window.Close()
There are 3 ways I "grow" PySimpleGUI and my own knowledge.
What is downright AMAZING about this program is that the way it is being shown to you is that each Text Element is Updated every time I read a webcam image and want to show it as ASCII. 48
If you missed the movie, here it is https://youtu.be/rzvJuz5bHTg
(4) I cheat and have some brilliant friends that help me out, or give me solutions. They deserve just as much credit as anything else listed here.
Believe it or not all that leads up to the topic of "Generating Layouts" which means Python code that creates a layout rather than it being created only by hand.
In the process of solving the problems above, especially the Reddit ones, I write more layouts, and have more opportunities to ponder more compact or more "Pythonic" (not found of tossing that word around) ways of doing things.
How to generate or create layouts differently than the brute force ways but rather by machine and by hand have not yet been added to the documentation. It's the hot topic for me today to finish.
Generating Layouts Demo ([Demo_Layout_Generation.py]
There are 8 different Design Patterns presented, although it'll be difficult for you to just copy and use them other than to study. Still, it's nice to have when you need to create a sh*t-load of buttons or input fields.
While used and not at all pointed out, I'll stress it in the docs, but keys can be ANYTHING. They're not limited to strings. This means they can hold something like (x,y) data. Each element in a matrix can have a key that is (row, col). The Questionnaire examples illustrate exactly what I'm talking about.
More Python Stuff, More Simple Coming....
Hoping to finish (miracles do happen) the readme and push out release(s) by the end of tomorrow.
There's a concept called "User Elements" that I don't see many people using that will be part of the docs too.
Plus even more Python stuff being looked at now. It's amazing what this language can do for this problem.
Generating Layouts Code
What the heck, the code for all these layouts isn't very large, so here it is. No download needed. Maybe it'll spark an idea in your head that I can take too.
import PySimpleGUI as sg """ Construct #0 - List comprehension to generate a row of Buttons Comprehensions are super-powers of Python. In this example we're using a comprehension to create 4 buttons that are all on the same row. """ def layout0(): layout = [[sg.Button(i) for i in range(4)]] # A list of buttons is created window = sg.Window('Generated Layouts', layout) event, values = window.Read() print(event, values) window.Close() """ Construct #1 - List comprehension to generate rows of Buttons More list super-power, this time used to build a series of buttons doing DOWN the window instead of across """ def layout1(): layout = [[sg.Button(i)] for i in range(4)] # a List of lists of buttons. Notice the ] after Button window = sg.Window('Generated Layouts', layout) event, values = window.Read() print(event, values) window.Close() """ Construct #2 - List comprehension to generate a row of Buttons and concatenation of more lines of elements Comprehensions are super-powers of Python. In this example we're using a comprehension to create 4 buttons that are all on the same row, just like the previous example. However, here, we want to not just have a row of buttons, we want have an OK button at the bottom. To do this, you "add" the rest of the GUI layout onto the end of the generated part. Note - you can't end the layout line after the +. If you wanted to put the OK button on the next line, you need to add a \ at the end of the first line. See next Construct on how to not use a \ that also results in a VISUALLY similar to a norma layout """ def layout2(): layout = [[sg.Button(i) for i in range(4)]] + [[sg.OK()]] # if want to split, can't add newline after + to do it window = sg.Window('Generated Layouts', layout) event, values = window.Read() print(event, values) window.Close() """ Construct # 3 - Adding together what appears to be 2 layouts Same as layout2, except that the OK button is put on another line without using a \ so that the layout appears to look like a normal, multiline layout without a \ at the end Also shown is the OLD tried and true way, using layout.append. You will see the append technique in many of the Demo programs and probably elsewhere. Hoping to remove these and instead use this more explicit method of +=. Using the + operator, as you've already seen, can be used in the middle of the layout. A call to append you cannot use this way because it modifies the layout list directly. """ def layout3(): # in terms of formatting, the layout to the RIGHT of the = sign looks like a 2-line GUI (ignore the layout += layout = [[sg.Button(i) for i in range(4)]] layout += [[sg.OK()]] # this row is better than, but is the same as layout.append([sg.Cancel()]) # .. this row in that they both add a new ROW with a button on it window = sg.Window('Generated Layouts', layout) event, values = window.Read() print(event, values) window.Close() """ Construct 4 - Using + to place Elements on the same row If you want to put elements on the same row, you can simply add them together. All that is happening is that the items in one list are added to the items in another. That's true for all these contructs using + """ def layout4(): layout = [[sg.Text('Enter some info')] + [sg.Input()] + [sg.Exit()]] window = sg.Window('Generated Layouts', layout) event, values = window.Read() print(event, values) window.Close() """ Construct #5 - Simple "concatenation" of layouts Layouts are lists of lists. Some of the examples and demo programs use a .append method to add rows to layouts. These will soono be replaced with this new technique. It's so simple that I don't know why it took so long to find it. This layout uses list comprehensions heavily, and even uses 2 of them. So, if you find them confusing, skip down to the next Construct and you'll see the same layout built except for loops are used rather than comprehensions The next 3 examples all use this same window that is layed out like this: Each row is: Text1, Text2, Radio1, Radio2, Radio3, Radio4, Radio5 Text1, Text2, Radio1, Radio2, Radio3, Radio4, Radio5 ... It shows, in particular, this handy bit of layout building, a += to add on additional rows. layout = [[stuff on row 1], [stuff on row 2]] layout += [[stuff on row 3]] Works as long as the things you are adding together look like this [[ ]] (the famous double bracket layouts of PSG) """ def layout5(): questions = ('Managing your day-to-day life', 'Coping with problems in your life?', 'Concentrating?', 'Get along with people in your family?', 'Get along with people outside your family?', 'Get along well in social situations?', 'Feel close to another person', 'Feel like you had someone to turn to if you needed help?', 'Felt confident in yourself?') layout = [[sg.T(qnum + 1, size=(2, 2)), sg.T(q, size=(30, 2))] + [sg.Radio('', group_id=qnum, size=(7, 2), key=(qnum, col)) for col in range(5)] for qnum, q in enumerate(questions)] layout += [[sg.OK()]] window = sg.Window('Computed Layout Questionnaire', layout) event, values = window.Read() print(event, values) window.Close() """ Construct #6 - Computed layout without using list comprehensions This layout is identical to Contruct #5. The difference is that rather than use list comprehensions, this code uses for loops. Perhaps if you're a beginner this version makes more sense? In this example we start with a "blank layout" [[ ]] and add onto it. Works as long as the things you are adding together look like this [[ ]] (the famous double bracket layouts of PSG) """ def layout6(): questions = ('Managing your day-to-day life', 'Coping with problems in your life?', 'Concentrating?', 'Get along with people in your family?', 'Get along with people outside your family?', 'Get along well in social situations?', 'Feel close to another person', 'Feel like you had someone to turn to if you needed help?', 'Felt confident in yourself?') layout = [] for qnum, question in enumerate(questions): # loop through questions row_layout = [sg.T(qnum + 1, size=(2, 2)), sg.T(question, size=(30, 2))] # rows start with # and question for radio_num in range(5): # loop through 5 radio buttons and add to row row_layout += [sg.Radio('', group_id=qnum, size=(7, 2), key=(qnum, radio_num))] layout += [row_layout] # after row is completed layout, tack it onto the end of final layout layout += [[sg.OK()]] # and finally, add a row to the bottom that has an OK button window = sg.Window('Computed Layout Questionnaire', layout) event, values = window.Read() print(event, values) window.Close() """ Construct #7 - * operator and list comprehensions Using the * operator from inside the layout List comprehension inside the layout Addition of rows to layouts All in a single variable assignment NOTE - this particular code, using the * operator, will not work on Python 2 and think it was added in Python 3.5 This code shows a bunch of questions with Radio Button choices There is a double-loop comprehension used. One that loops through the questions (rows) and the other loops through the Radio Button choices. Thus each row is: Text1, Text2, Radio1, Radio2, Radio3, Radio4, Radio5 Text1, Text2, Radio1, Radio2, Radio3, Radio4, Radio5 Text1, Text2, Radio1, Radio2, Radio3, Radio4, Radio5 What the * operator is doing in these cases is expanding the list they are in front of into a SERIES of items from the list... one after another, as if they are separated with comma. It's a way of "unpacking" from within a statement. The result is a beautifully compact way to make a layout, still using a layout variable, that consists of a variable number of rows and a variable number of columns in each row. """ def layout7(): questions = ('Managing your day-to-day life', 'Coping with problems in your life?', 'Concentrating?', 'Get along with people in your family?', 'Get along with people outside your family?', 'Get along well in social situations?', 'Feel close to another person', 'Feel like you had someone to turn to if you needed help?', 'Felt confident in yourself?') layout = [[*[sg.T(qnum + 1, size=(2, 2)), sg.T(q, size=(30, 2))], # These are the question # and the question text *[sg.Radio('', group_id=qnum, size=(7, 2), key=(qnum, col)) for col in range(5)]] for qnum, q in enumerate(questions)] + [[sg.OK()]] # finally add an OK button at the very bottom by using the '+' operator window = sg.Window('Questionnaire', layout) event, values = window.Read() print(event, values) window.Close() # ------------------------- Call each of the Constructs ------------------------- layout0() layout1() layout2() layout3() layout4() layout5() layout6() layout7()
More Fun Collapsing Code - Replacing
YouTube Tutorial That Includes PySimpleGUI GUI
I spotted a new video on YouTube that uses PySimpleGUI.
He did a nice thing by adding an index in the description to the location it can be found in the video. He's using it in an OO design, so it was really interesting to see how he split things up.
I learn something every time I see someone else's code.
It was nice to hear some kind words about PySimpleGUI. No complaints at all. Just reinforcement that it's simple.
Release PySimpleGUI 4.2 and PySimpleGUI27 2.2
The cool lookup release! No more need for FindElement. You can continue to use FindElement.
Coming soon.... PEP8 compliant interfaces
The latest 4.2 release has with it these new
Starting with Windows as these methods are what tend to be called the most. The Update methods for the elements are the 2nd most called and they can be dropped completely now by directly calling the element. I'll still add all the
I hope to have a bunch more done this week. So, if TheCamelCaseMethod and CamelCaseFuncton names are driving you crazy, then don't worry, a fix is otw.
You can call:
That should take care of 70% of the PySimpleGUI programs out there.
PEP8 Compliant Interfaces for PySimpleGUI is Done!
The tkinter port of PySimpleGUI now has PEP8 named method and function names. All of the user accessable methods and functions have a new PEP8 compliant name in addition to the original names.
In other words, all of your old code continues to operate as it did before. You could even mix them if you wanted. Maybe you like the way
Assuming all goes well, you can expect this to be cross-ported quickly and released to PyPI.
I go surfing for comments from time to time, just to see how the world is liking or hating PySimpleGUI. Thankfully, 99% of the comments I see posted are positive. Only recently have I taken a moment to notice that this is happening on a daily basis more and more.
Twitter I don't check as often as StackOverflow for example, but I do check it on occassion. Tonight I was treated to this surprising tweet:
And, no, I didn't pay him to say "after reading the docs", but I did thank him of course.
You guys/gals are the best user community on GitHub!
Legacy Python (2.7) Users Need to Begin Planning
As is discussed in the documentation, the Python 2.7 version of PySimpleGUI will cease to exist on Jan 1 2020. There will be no copes on this GitHub. The final 2.7 release will be left up on PyPI, but no new additions nor patches will be made.
"Cease to exist" = rm PySimpleGUI27*
In the coming weeks the final PySimpleGUI27.py file will be frozen, hopefully at a nice place in terms of the features you want.After the freeze, there will be no updates passed over from the PySimpleGUI.py work.
4.3 PySimpleGUI Release 22-Aug-2019
PEP8 PEP8 PEP8