GooeyTurn (almost) any Python 2 or 3 Console Program into a GUI application with one line
Support this project![]() Table of Contents
Quick StartInstallation instructionsThe easiest way to install Gooey is via pip install Gooey Alternatively, you can install Gooey by cloning the project to your local directory git clone https://github.com/chriskiehl/Gooey.git run python setup.py install NOTE: Python 2 users must manually install WxPython! Unfortunately, this cannot be done as part of the pip installation and should be manually downloaded from the wxPython website. UsageGooey is attached to your code via a simple decorator on whichever method has your from gooey import Gooey @Gooey <--- all it takes! :) def main(): parser = ArgumentParser(...) # rest of code Different styling and functionality can be configured by passing arguments into the decorator. # options
@Gooey(advanced=Boolean, # toggle whether to show advanced config or not
language=language_string, # Translations configurable via json
auto_start=True, # skip config screens all together
target=executable_cmd, # Explicitly set the subprocess executable arguments
program_name='name', # Defaults to script name
program_description, # Defaults to ArgParse Description
default_size=(610, 530), # starting size of the GUI
required_cols=1, # number of columns in the 'Required' section
optional_cols=2, # number of columns in the 'Optional' section
dump_build_config=False, # Dump the JSON Gooey uses to configure itself
load_build_config=None, # Loads a JSON Gooey-generated configuration
monospace_display=False) # Uses a mono-spaced font in the output screen
)
def main():
parser = ArgumentParser(...)
# rest of code See: How does it Work section for details on each option. Gooey will do its best to choose sensible widget defaults to display in the GUI. However, if more fine tuning is desired, you can use the drop-in replacement from gooey import Gooey, GooeyParser @Gooey def main(): parser = GooeyParser(description='My Cool GUI Program!') parser.add_argument('Filename', widget='FileChooser') parser.add_argument('Date', widget='DateChooser') ... ExamplesGooey downloaded and installed? Great! Wanna see it in action? Head over the the Examples Repository to download a few ready-to-go example scripts. They'll give you a quick tour of all Gooey's various layouts, widgets, and features. What is it?Gooey converts your Console Applications into end-user-friendly GUI applications. It lets you focus on building robust, configurable programs in a familiar way, all without having to worry about how it will be presented to and interacted with by your average user. Why?Because as much as we love the command prompt, the rest of the world looks at it like an ugly relic from the early '80s. On top of that, more often than not programs need to do more than just one thing, and that means giving options, which previously meant either building a GUI, or trying to explain how to supply arguments to a Console Application. Gooey was made to (hopefully) solve those problems. It makes programs easy to use, and pretty to look at! Who is this for?If you're building utilities for yourself, other programmers, or something which produces a result that you want to capture and pipe over to another console application (e.g. *nix philosophy utils), Gooey probably isn't the tool for you. However, if you're building 'run and done,' around-the-office-style scripts, things that shovel bits from point A to point B, or simply something that's targeted at a non-programmer, Gooey is the perfect tool for the job. It lets you build as complex of an application as your heart desires all while getting the GUI side for free. How does it work?Gooey is attached to your code via a simple decorator on whichever method has your @Gooey
def my_run_func():
parser = ArgumentParser(...)
# rest of code At run-time, it parses your Python script for all references to Mappings:Gooey does its best to choose sensible defaults based on the options it finds. Currently,
GooeyParserIf the above defaults aren't cutting it, you can control the exact widget type by using the drop-in Example: from argparse import ArgumentParser .... def main(): parser = ArgumentParser(description='My Cool Gooey App!') parser.add_argument('filename', help='name of the file to process') Given then above, Gooey would select a normal
However, by dropping in from gooey import GooeyParser
....
def main():
parser = GooeyParser(description='My Cool Gooey App!')
parser.add_argument('filename', help='name of the file to process', widget='FileChooser') Custom Widgets:
Internationalization![]() Gooey is international ready and easily ported to your host language. Languages are controlled via an argument to the @Gooey(language='russian') def main(): ... All program text is stored externally in Thanks to some awesome contributers, Gooey currently comes pre-stocked with over 18 different translations! Want to add another one? Submit a pull request! Global ConfigurationJust about everything in Gooey's overall look and feel can be customized by passing arguments to the decorator.
Layout CustomizationYou can achieve fairly flexible layouts with Gooey by using a few simple customizations. At the highest level, you have several overall layout options controllable via various arguments to the Gooey decorator.
Grouping Inputs By default, if you're using Argparse with Gooey, your inputs will be split into two buckets: With ![]() parser = ArgumentParser()
search_group = parser.add_argument_group(
'Search Options',
'Customize the search options'
) You can add arguments to the group as normal search_group.add_argument( '--query', help='Base search string' ) Which will display them as part of the group within the UI. Run ModesGooey has a handful of presentation modes so you can tailor its layout to your content type and user's level or experience. AdvancedThe default view is the 'full' or 'advanced' configuration screen. It has two different layouts depending on the type of command line interface it's wrapping. For most applications, the flat layout will be the one to go with, as its layout matches best to the familiar CLI schema of a primary command followed by many options (e.g. Curl, FFMPEG). On the other side is the Column Layout. This one is best suited for CLIs that have multiple paths or are made up of multiple little tools each with their own arguments and options (think: git). It displays the primary paths along the left column, and their corresponding arguments in the right. This is a great way to package a lot of varied functionality into a single app.
Both views present each action in the Setting the layout style: Currently, the layouts can't be explicitly specified via a parameter (on the TODO!). The layouts are built depending on whether or not there are It can be toggled via the @gooey(advanced=True)
def main():
# rest of code BasicThe basic view is best for times when the user is familiar with Console Applications, but you still want to present something a little more polished than a simple terminal. The basic display is accessed by setting the @gooey(advanced=False) def main(): # rest of code
No ConfigNo Config pretty much does what you'd expect: it doesn't show a configuration screen. It hops right to the
Menus
You can add a Menu Bar to the top of Gooey with customized menu groups and items. Menus are specified on the main @Gooey(menu=[{}, {}, ...]) Each map is made up of two key/value pairs
You can have as many menu groups as you want. They're passed as a list to the @Gooey(menu=[{'name': 'File', 'items: []}, {'name': 'Tools', 'items': []}, {'name': 'Help', 'items': []}]) Individual menu items in a group are also just maps of key / value pairs. Their exact key set varies based on their
Currently, three types of menu options are supported:
![]() About Dialog is your run-of-the-mill About Dialog. It displays program information such as name, version, and license info in a standard native AboutBox. Schema
Example: {
'type': 'AboutDialog',
'menuTitle': 'About',
'name': 'Gooey Layout Demo',
'description': 'An example of Gooey\'s layout flexibility',
'version': '1.2.1',
'copyright': '2018',
'website': 'https://github.com/chriskiehl/Gooey',
'developer': 'http:///',
'license': 'MIT'
} ![]() MessageDialog is a generic informational dialog box. You can display anything from small alerts, to long-form informational text to the user. Schema:
Example: { 'type': 'MessageDialog', 'menuTitle': 'Information', 'message': 'Hey, here is some cool info for ya!', 'caption': 'Stuff you should know' } Link is for sending the user to an external website. This will spawn their default browser at the URL you specify. Schema:
Example: {
'type': 'Link',
'menuTitle': 'Visit Out Site',
'url': 'http://www.'
} A full example: Two menu groups ('File' and 'Help') with four menu items between them. @Gooey( program_name='Advanced Layout Groups', menu=[{ 'name': 'File', 'items': [{ 'type': 'AboutDialog', 'menuTitle': 'About', 'name': 'Gooey Layout Demo', 'description': 'An example of Gooey\'s layout flexibility', 'version': '1.2.1', 'copyright': '2018', 'website': 'https://github.com/chriskiehl/Gooey', 'developer': 'http:///', 'license': 'MIT' }, { 'type': 'MessageDialog', 'menuTitle': 'Information', 'caption': 'My Message', 'message': 'I am demoing an informational dialog!' }, { 'type': 'Link', 'menuTitle': 'Visit Our Site', 'url': 'https://github.com/chriskiehl/Gooey' }] },{ 'name': 'Help', 'items': [{ 'type': 'Link', 'menuTitle': 'Documentation', 'url': 'https://www./foo' }] }] ) Input Validation![]()
Gooey can optionally do some basic pre-flight validation on user input. Internally, it uses these validator functions to check for the presence of required arguments. However, by using GooeyParser, you can extend these functions with your own validation rules. This allows Gooey to show much, much more user friendly feedback before it hands control off to your program. Writing a validator: Validators are specified as part of the
e.g. gooey_options={
'validator':{
'test': 'len(user_input) > 3',
'message': 'some helpful message'
}
} The Your test function can be made up of any valid Python expression. It receives the variable Full Code Example from gooey.python_bindings.gooey_decorator import Gooey from gooey.python_bindings.gooey_parser import GooeyParser @Gooey def main(): parser = GooeyParser(description='Example validator') parser.add_argument( 'secret', metavar='Super Secret Number', help='A number specifically between 2 and 14', gooey_options={ 'validator': { 'test': '2 <= int(user_input) <= 14', 'message': 'Must be between 2 and 14' } }) args = parser.parse_args() print('Cool! Your secret number is: ', args.secret) ![]() With the validator in place, Gooey can present the error messages next to the relevant input field if any validators fail. Using Dynamic Values
Gooey's Choice style fields (Dropdown, Listbox) can be fed a dynamic set of values at runtime by enabling the How does it work? ![]() At runtime, whenever the user hits the Configuration screen, Gooey will call your program with a single CLI argument: For example, assuming a setup where you have a dropdown that lists user files: ...
parser.add_argument(
'--load',
metavar='Load Previous Save',
help='Load a Previous save file',
dest='filename',
widget='Dropdown',
choices=list_savefiles(),
) Here the input we want to populate is {'--load': ['Filename_1.txt', 'filename_2.txt', ..., 'filename_n.txt]} Checkout the full example code in the Examples Repository. Or checkout a larger example in the silly little tool that spawned this feature: SavingOverIt. Showing Progress![]() Giving visual progress feedback with Gooey is easy! If you're already displaying textual progress updates, you can tell Gooey to hook into that existing output in order to power its Progress Bar. For simple cases, output strings which resolve to a numeric representation of the completion percentage (e.g. For more complicated outputs, you can pass in a custom evaluation expression ( Output strings which satisfy the regular expression can be hidden from the console via the Regex and Processing Expression @Gooey(progress_regex=r'^progress: (?P<current>\d )/(?P<total>\d )$',
progress_expr='current / total * 100') Program Output: progress: 1/100 progress: 2/100 progress: 3/100 ... There are lots of options for telling Gooey about progress as your program is running. Checkout the Gooey Examples repository for more detailed usage and examples! Elapsed / Remaining TimeGooey also supports tracking elapsed / remaining time when progress is used! This is done in a similar manner to that of the project tqdm. This can be enabled with @Gooey(progress_regex=r'^progress: (?P<current>\d )/(?P<total>\d )$',
progress_expr='current / total * 100',
timing_options = {
'show_time_remaining':True,
'hide_time_remaining_on_complete':True,
}) Customizing IconsGooey comes with a set of six default icons. These can be overridden with your own custom images/icons by telling Gooey to search additional directories when initializing. This is done via the @Gooey(program_name='Custom icon demo', image_dir='/path/to/my/image/directory') def main(): # rest of program Images are discovered by Gooey based on their filenames. So, for example, in order to supply a custom configuration icon, simply place an image with the filename
PackagingThanks to some awesome contributers, packaging Gooey as an executable is super easy. The tl;dr pyinstaller version is to drop this build.spec into the root directory of your application. Edit its contents so that the Detailed step by step instructions can be found here. Screenshots
Wanna help?Code, translation, documentation, or graphics? All pull requests are welcome. Just make sure to checkout the contributing guidelines first. |
|
来自: 新用户61024634 > 《py office》