Sometimes, we write some simple and useful little code. At this point, if you can have a visual GUI interface, is it very comfortable. A Python library introduced today is super awesome. A few lines of code can realize a visual interface!
Gooey introduction
A third-party package Gooey is used here. It only needs one line of code to convert Python programs into graphical interface applications [add decorator functions and add a few additional parameters]
Gooey is a Python GUI program development framework based on the wxPython GUI library. The use method is similar to the Python built-in CLI development library argparse. You can quickly convert the console program into GUI application with one line of code.
① Installation mode
pip install Gooey
② A simple example
Gooey attaches a simple decorator to the main function, and then uses GooeyParser to visualize all the parameters you need as text boxes, selection boxes and even file selection boxes.
from gooey import Gooey, GooeyParser @Gooey def main(): parser = GooeyParser(description="My GUI Program!") parser.add_argument('Filename', widget="FileChooser") # File selection box parser.add_argument('Date', widget="DateChooser") # Date selection box args = parser.parse_args() # Receive parameters passed from the interface print(args) if __name__ == '__main__': main()
The results are as follows:
We can also configure different styles and functions by passing parameters to the decorator.
@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 )
Two simple controls have been used above: FileChooser and DateChooser, which provide the functions of "file selector" and "date selector" respectively. In Gooey, the currently supported chooser class controls are:
The configuration parameters are mainly used to globally configure the Gooey interface. The configuration methods are as follows:
@Gooey(program_name='Demo') def function(): pass
And program_ Like the name parameter configuration, Gooey also supports many other configurations. The following is the list of parameters it supports:
Case introduction
For example, we want to make an automatic file sorting program. As shown in the figure, there are such a pile of messy files that we need to classify the same types of files.
At this time, you can think about it. There needs to be a file selection box on the visual interface. After we select the corresponding folder and click start, we can realize the final file classification. Isn't it beautiful?
So how to use this library to achieve this function?
# Import related libraries import os import glob import shutil from gooey import Gooey, GooeyParser # Define a file dictionary. Different file types belong to different folders, with a total of 9 categories. file_dict = { 'picture': ['jpg', 'png', 'gif', 'webp'], 'video': ['rmvb', 'mp4', 'avi', 'mkv', 'flv'], "audio frequency": ['cd', 'wave', 'aiff', 'mpeg', 'mp3', 'mpeg-4'], 'file': ['xls', 'xlsx', 'csv', 'doc', 'docx', 'ppt', 'pptx', 'pdf', 'txt'], 'Compressed file': ['7z', 'ace', 'bz', 'jar', 'rar', 'tar', 'zip', 'gz'], 'Common formats': ['json', 'xml', 'md', 'ximd'], 'Program script': ['py', 'java', 'html', 'sql', 'r', 'css', 'cpp', 'c', 'sas', 'js', 'go'], 'Executable program': ['exe', 'bat', 'lnk', 'sys', 'com'], 'Font file': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2'] } # Define a function to pass in the suffix corresponding to each file. Determine whether the file exists in the dictionary file_ In dict; # If it exists, the corresponding folder name is returned; If it does not exist, name the folder "unknown classification"; def func(suffix): for name, type_list in file_dict.items(): if suffix.lower() in type_list: return name return "Unknown classification" @Gooey(encoding='utf-8', program_name="Organize files gadget-V1.0.0\n\n official account:The beauty of data analysis and statistics", language='chinese') def start(): parser = GooeyParser() parser.add_argument("path", help="Please select the file path to organize:", widget="DirChooser") # Be sure to use double quotation marks, otherwise there is no such attribute args = parser.parse_args() # print(args, flush=True) # Pit point: flush=True will be used when packing return args if __name__ == '__main__': args = start() path = args.path # Recursively obtain all files and folders under "pending file path". for file in glob.glob(f"{path}/**/*", recursive=True): # Since we classify documents, we need to select documents here. if os.path.isfile(file): # Due to the isfile() function, the full path of each file is obtained. Here, call the basename() function to get the file name directly; file_name = os.path.basename(file) suffix = file_name.split(".")[-1] # Determine whether the "file name" is in the dictionary. name = func(suffix) # print(func(suffix)) # Create corresponding folders according to each file classification. if not os.path.exists(f"{path}\\{name}"): os.mkdir(f"{path}\\{name}") # Copy the files to their respective folders. shutil.copy(file, f"{path}\\{name}")
The final effect is as follows:
Carefully observe the above code. There are few lines of code related to the production of GUI interface. Is it super convenient to make a simple tool?