In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use PySimpleGUI to add GUI to programs and scripts. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
For program files of type .exe, we can open them by double-clicking the left mouse button, but for Python programs of type .py, almost no one will try the same thing. For a typical (non-programmer) user, a form that can interact is expected to pop up when they double-click to open the .exe file. Based on Tkinter, you can provide GUI through a standard Python installation of standard Python installations, but many programs are unlikely to do so.
What if it becomes so easy to open a Python program and enter the GUI interface that a real beginner can master it? Will anyone be interested and use it? This is a difficult question to answer, because even today it is not easy to create a custom GUI layout.
There seems to be a "mismatch" of capabilities when it comes to adding GUI to programs or scripts. Real beginners are forced to use the command-line approach, and many advanced programmers are reluctant to take the time to create a Tkinter GUI.
GUI framework
There are many GUI frameworks of Python, among which Tkinter,wxPython,Qt and Kivy are several mainstream frameworks. In addition, there are many simplified frameworks encapsulated on the basis of the above frameworks, such as EasyGUI,PyGUI and Pyforms.
But the problem is that for beginners (in this case, users with less than six months of programming experience), they can't start with even the simplest mainstream frameworks; they can choose encapsulated (simplified) frameworks, but it's still hard or even impossible to create a custom GUI layout layout. Even if you learn some kind of (simplified) framework, you need to write a lot of code.
PySimpleGUI tries to solve the above GUI conundrum by providing a simple, easy to understand, and easy to customize GUI interface. If you use PySimpleGUI, many complex GUI require less than 20 lines of code.
Secret
The secret that PySimpleGUI is perfect for beginners is that it already contains most of the code that would otherwise have been written by the user. PySimpleGUI handles button callback callback without user writing code. For beginners, it is not easy to master the concept of functions in a few weeks, and it seems a bit difficult for them to understand callback functions.
In most GUI frameworks, laying out the GUI widget widgets usually requires some code to be written, with at least 1-2 lines per widget. PySimpleGUI uses "auto-packer" technology to create layouts automatically. As a result, pack or grid systems are no longer required to lay out GUI windows.
(LCTT translation note: the pack and grid mentioned here are both layout managers for Tkinter, and the other is called place. )
*, the PySimpleGUI framework makes effective use of Python language features to reduce the amount of user code and simplify the way GUI data is returned. When you create a widget in a form's form layout, the widget is deployed to the corresponding layout without additional code.
What is GUI?
Most GUI does only one thing: collect user data and return it. From the programmer's point of view, it can be summarized as the following function calls:
Button, values = GUI_Display (gui_layout)
Most of the user behaviors supported by GUI include mouse clicks (for example, "confirm", "cancel", "save", "yes" and "no", etc.) and content input. GUI essentially boils down to one line of code.
This is how PySimpleGUI (the simple GUI mode) works. When the command displays GUI, no code will be executed unless you click to close the form.
Of course, there are more complex GUI, in which the window does not close after a mouse click; for example, the robot's remote control interface, chat window, and so on. Such complex forms can also be created in PySimpleGUI.
Quickly create GUI
When will PySimpleGUI be useful? Obviously, that's when you need GUI. It takes no more than 5 minutes for you to create and try GUI. The easiest way to create a GUI is to copy a copy of the code from a classic instance of PySimpleGUI. The specific operation procedure is as follows:
Find a GUI that is closest to your needs
Copy code from a classic example
Paste into IDE and run
Let's take a look at recipe, a classic example in the book:
Import PySimpleGUI as sg # Very basic form. Return values as a listform = sg.FlexForm ('Simple data entry form') # begin with a blank form layout = [sg.Text (' Please enter your Name, Address, Phone')], [sg.Text ('Name', size= (15,1)), sg.InputText (' name')], [sg.Text ('Address', size= (15,1)), sg.InputText (' address')], [sg.Text ('Phone', size= (15)] ), sg.InputText ('phone')], [sg.Submit (), sg.Cancel ()]] button, values = form.LayoutAndRead (layout) print (button, values [0], values [1], values [2])
After running, a medium-sized form opens.
If you just want to collect some string type values, copy the code from the above classic example and modify it slightly to meet your needs.
You can even create a custom GUI layout with just five lines of code.
Import PySimpleGUI as sg form = sg.FlexForm ('My first GUI') layout = [[sg.Text ('Enter your name'), sg.InputText ()], [sg.OK ()]] button, (name,) = form.LayoutAndRead (layout)
Create a custom GUI in 5 minutes
On the basis of a simple layout, you can use PySimpleGUI to create a custom layout within 5 minutes by modifying the code in the classic example.
In PySimpleGUI, the widget widgets is called the element elements. The name of the element is consistent with the name used in the encoding.
(LCTT Note: the word widget is used in Tkinter)
Core element TextInputTextMultilineInputComboListboxRadioCheckboxSpinOutputSimpleButtonRealtimeButtonReadFormButtonProgressBarImageSliderColumn element abbreviation
PySimpleGUI also contains two ways to abbreviate elements. One is the abbreviation of the element type name, such as T as the abbreviation for Text; the other is that the element parameter is configured with a default value, so you don't have to specify all the parameters, for example, the default text of the Submit button is "Submit".
T = TextTxt = TextIn = InputTextInput = IntputTextCombo = InputComboDropDown = InputComboDrop = InputCombo
(LCTT translation note: * the abbreviation is an alias for the Python class, and the second abbreviation specifies the default value of the parameter when returning the Python function definition of the element object)
Button abbreviation
Some general purpose buttons have shorthand implementations, including:
FolderBrowseFileBrowseFileSaveAsSaveSubmitOKOk (where `k` is lowercase) CancelQuitExitYesNo
In addition, there is an abbreviation for the general button function:
SimpleButtonReadFormButtonRealtimeButton
(LCTT translation note: it is actually a function that returns an instance of the Button class)
These are all the elements supported by PySimpleGUI. If it is not in the above list, it will not take effect in your window layout.
(LCTT translation note: the above are the class names, category names, or functions that return instances of PySimpleGUI, so you can only use those in the list. )
GUI design pattern
For GUI programs, the calls to create and display windows are more or less the same, except in the layout of the elements.
The design pattern code is basically the same as the example above, except that the layout is removed:
Import PySimpleGUI as sg form = sg.FlexForm ('Simple data entry form') # Define your form here (it's a list of lists) button, values = form.LayoutAndRead (layout)
(LCTT translation note: this code does not run, just to illustrate the design patterns that every program uses. )
For most GUI, the coding process is as follows:
Create a form object
Define GUI in the form of "list of lists"
Show GUI and get the value of the element
The above process corresponds to the code in the PySimpleGUI design pattern section one by one.
GUI layout
To create a custom GUI, first split the form into multiple rows, because the form is defined one by one. Then, place the elements in each row from left to right.
What we get is a "list of lists", similar to this:
Layout = [Text ('Row 1')], [Text (' Row 2'), Checkbox ('Checkbox 1), OK (), Checkbox (' Checkbox 2'), OK ()]]
The corresponding effect of the above layout is as follows:
Show GUI
When you have finished laying out and copying the code used to create and display the form, the next step is to display the form and collect user data.
The following line of code shows the form and returns the collected data:
Button, values = form.LayoutAndRead (layout)
The result returned by the form consists of two parts: one is the name of the button being clicked, and the other is a list containing the values entered by all users in the form.
In this example, after the form is displayed, the user directly clicks the "OK" button, and the result is as follows:
Button = 'OK'values = = [False, False]
The Checkbox type element returns a value of type True or False. Because it is unchecked by default, the value of both elements is False.
Display the value of the element
Once you get the return value from GUI, it's a good idea to check the value in the return variable. Instead of using the print statement to print, we might as well stick to GUI and output these values in a window.
(LCTT translation note: consider using the Python 3 version, print should be a function, not a statement. )
There are a variety of message boxes to choose from in PySimpleGUI. The data passed to the message box (function) is displayed in the message box; the function can accept any number of parameters, and you can easily display all the variables you want to view.
In PySimpleGUI, the most commonly used message box is MsgBox. To show the data in the example above, just write one line of code:
MsgBox ('The GUI returned:', button, values) integration
Well, now that you know the basics, let's create a form that contains as many PySimpleGUI elements as possible. In addition, in order to get a better look and feel, we will use a green / tan color scheme.
Import PySimpleGUI as sg sg.ChangeLookAndFeel ('GreenTan') form = sg.FlexForm (' Everything bagel', default_element_size= (40,1)) column1 = [[sg.Text ('Column 1cow, background_color='#d3dfda', justification='center', size= (10jue 1))], [sg.Spin (' Spin Box 1Qing, '2mom,' 3'), initial_value='Spin Box 1'), [sg.Spin ('Spin Box 1Qing,' 2'),'2' '3'), initial_value='Spin Box 2')], [sg.Spin (' Spin Box 1,'2,'3'), initial_value='Spin Box 3')]] layout = [[sg.Text ('All graphic widgets in one formalization, size= (30,1), font= ("Helvetica", 25))], [sg.Text (' Here is some text....) And a place to enter text'), [sg.InputText ('This is my text')], [sg.Checkbox (' My first checkboxes'), sg.Checkbox ('My second checkboxes, default=True)], [sg.Radio ('My first radiated boxes, "RADIO1", default=True), sg.Radio ('My second radiated boxes, "" RADIO1 ")], [sg.Multiline (default_text='This is the default Text should you decide not to type anything', size= (35,3) Sg.Multiline (default_text='A second multi-line', size= (35,3)), [sg.InputCombo ('Combobox 1,' Combobox 2'), size= (20, 3)), sg.Slider (range= (1,100), orientation='h', size= (34, 20), default_value=85)], [sg.Listbox ('Listbox 1,' Listbox 2), 'Listbox 3'), size= (30, 3), sg.Slider (range= (1)) ), orientation='v', size= (5,20), default_value=25), sg.Slider (range= (1,100), orientation='v', size= (5,20), default_value=75), sg.Slider (range= (1,100), orientation='v', size= (5,20), default_value=10), sg.Column (column1, background_color='#d3dfda')], [sg.Text ('_ * 80)], [sg.Text ('Choose A Folder', size= (35)) ], [sg.Text ('Your Folder', size= (15,1), auto_size_text=False, justification='right'), sg.InputText (' Default Folder'), sg.FolderBrowse ()], [sg.Submit (), sg.Cancel ()]] button, values = form.LayoutAndRead (layout) sg.MsgBox (button, values)
Look, there's a lot of code to write above, but if you try to implement the same GUI directly using the Tkinter framework, you'll soon see how concise the PySimpleGUI version of the code is.
The * * line of the code opens a message box with the following effect:
The contents of each parameter in the message box function are printed to a separate line. The message box in this example contains two lines, the second of which is very long and contains a nested list.
It is recommended that you take a moment to compare the above results with the elements in GUI so that you can better understand how these results are produced.
Add GUI to your program or script
If you have a script used on the command line, adding GUI does not necessarily mean abandoning the script altogether. A simple scenario is as follows: if the script does not require command-line arguments, you can call the script directly using GUI; instead, run the script the way it was.
You only need logic similar to the following:
If len (sys.argv) = = 1: # collect arguments from GUIelse: # collect arguements from sys.argv
The easiest way to create and run GUI is to copy a copy of the code from the classic instance of PySimpleGUI and modify it.
Come and try it! Add some fun to scripts that you've been tired of executing manually. It only takes 5-10 minutes to play the sample script. You may find a classic example that almost meets your needs; if you can't find it, it's easy to write one yourself. Even if you really can't play, it's only a waste of 5-10 minutes.
Resource installation mode
Systems that support Tkinter support PySimpleGUI, even raspberry pie Raspberry Pi, but you need to use Python 3.
Pip install PySimpleGUI on "how to use PySimpleGUI to add GUI to programs and scripts" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.