web123456

(Part2) A small program written in Python to calculate the number of parking spaces with a specific number skipped and packaged into an executable file with a GUI interface using wxPython.

1. Overview

This article focuses on the use of Python to write a small program that can calculate the number of skipped parking spaces with a specific number. It also utilizes a third-party library, wxPython.GUI interface, packaged into an executable file.

In reality, there is such a practical case, the number of underground garage of a building has more than 2,000 parking spaces, the parking spaces are divided into five sub-districts, each sub-district has 400-500 parking spaces ranging in number. And the number of parking spaces has been programmed on the map one by one, for example, the starting number is 001, the termination number is 720, but the marketing personnel in the preparation of the number of parking spaces to avoid the number of parking spaces with the number 4 and the number of numbers 18, for example, 4, 14, 18, 24, 40, 118, 114, etc., so that we can not be directly used to terminate the number minus the number of the starting number and then add the number of one algorithm to calculate out the number of parking spaces.

So to make it easier to count the total number of parking spaces for this kind of number hopping, I wrote this simple code. This code utilizes very basic python knowledge, such as string manipulation, list manipulation, for loops, input functions, custom functions and so on, from shallow to deep gradually improve the whole code. It's very suitable for Python beginners who have just finished learning list and string related operations to practice using. wxPython part of the application is also very basic usage, mainly user input text box, static text, and the basics of button control.

In order to facilitate the use of this widget for people who don't know how to use Python and don't have a Python development environment on their computers, we need to make a GUI interface and package it as aexecutable file

2.Code realization

(1) Python environment code implementation

This section is detailed in my other article:A small program written in Python to calculate the number of parking spaces skipped with a specific number and packaged as an executable using wxPython to make a GUI interface (Part1)

(2) wxPython create GUI interface

① Introduction to wxPython

wxPython is an excellent set of GUI graphics library for the Python language. It allows Python programmers to easily create complete, full-featured GUIs.user. (# originating fromBaidu online encyclopedia

② Install wxPython

wxPython is a third-party library for Python that needs to be installed with pip, as in the following code:

pip install wxpython

③ Create a simple window

The following code is the basic code to create a window, see the comments in the code for details:

  1. import wx # Import wxpython modules
  2. class MyFrame(): # Define a subclass to give us more control over the content and appearance of the window.
  3. def __init__(self): # Define initialization methods
  4. # Set the title and size of the frame
  5. .__init__(self, None, -1, title='Calculate the number of parking spaces applet', size=(400, 300))
  6. # Run as main program
  7. if __name__ == '__main__':
  8. app = () # Create an application instance
  9. frame = MyFrame() # Example of creating a window
  10. () # Make the window visible
  11. () # Call the MainLoop() method of the application instance to enter the main event loop

The above code runs and creates a window as shown below:

④ Add controls to the window

Next we add controls on this window, add controls need to add the canvas first, all the controls are laid out to the canvas, add the canvas code is as follows, where -1 for the ID value, you can customize, you can also use -1 by wxPython to automatically generate a new ID.

panel = (self, -1)
can create static text with the following constructor:
(parent, id, label, pos=,size=, style=0, name=”staticText”)
         The individual parameters of the constructor are as follows:
parent:Parent window widget.
id:Identifier. Using -1 automatically creates a unique identifier.
label:You want to display the text in a static control.
pos:One or a Python tuple which is the location of the window widget.
size:One or a Python tuple which is the size of the window widget.
style:Style tags.
name:The name of the object for lookup purposes.
The following code is the static text we created:
(panel, -1, 'Please enter the starting parking space number', pos=(30, 30))
The constructor of the class can create a single line text input box with the following constructor:
(parent, id, value = ””, pos=, size=, style=0, validator=,name=)
         The parameters in the constructor of a class are almost the same as the parameters of the constructor of the label has been changed to value.value is the initial text displayed in the control. The class also has an additional validator parameter, this
Used to override data to ensure that only the data to be accepted is typed.
The following is the code that creates the text input:
self.start_no_text = (panel, -1, '001', pos=(150, 30), size=(100, -1))

The code runs as shown below:

In this way, we have created a good static text and input text box, next we put the other static text and input text box to create a piece of the following code:
  1. # Add static text, set parent container to panel, ID value to -1, display text content and position
  2. (panel, -1, 'Please enter the starting parking space number', pos=(30, 30))
  3. (panel, -1, 'Please enter the termination parking space number', pos=(30, 60))
  4. (panel, -1, 'Enter the digits not included in the number, separated by commas', pos=(30, 90))
  5. (panel, -1, 'Enter the digits to be skipped in the number, separated by commas', pos=(30, 150))
  6. (panel, -1, 'The total number of parking spaces is', pos=(30, 240))
  7. # Add input text box, set parent container as panel, ID value as -1, default text content, position and size
  8. self.start_no_text = (panel, -1, '001', pos=(150, 25), size=(100, -1))
  9. self.end_no_text = (panel, -1, pos=(150, 55), size=(100, -1))
  10. self.not_in_no_text = (panel, -1, pos=(30, 115), size=(220, -1))
  11. self.pass_no_text = (panel, -1, pos=(30, 175), size=(220, -1))
  12. self.total_no_text = (panel, -1, pos=(150, 235), size=(100, -1))

The effect after running is as follows:

I'll add the button control below.The constructor creates the button, which has the following constructor:

(parent, id, label, pos, size=wxDefaultSize, style=0, validator, name=”button”)
        The parameters in the constructor are the same as those in the Without expanding on the constructor, here is the code to create our button:
 = (panel, -1, 'Click me for calculations', pos=(30, 205), size=(220, -1))

The effect of running after adding is as follows:

From the effect the button looks too close to the text box, to emphasize the button we create a font thatFonts are classesto create a font instance, use the following constructor:

(pointSize, family, style, weight, underline=False, faceName=””,encoding=wx.FONTENCODING_DEFAULT)
pointSize is the integer size of the font in pounds.
familyis used to quickly specify a font without having to know the actual name of the font.The exact selection of fonts depends on the system and the specific fonts available, the available values are: ,,,,,。
style parameter specifies whether the font is skewed or not, and its values are: , , , and respond in singing
weightparameter specifies the eye-catchingness of the font degree, optional values are available: , , maybe
underline parameter only works on the On Windows systems, if the value is True and underlined. False is not underlined.
faceName The parameter specifies the font name.
encoding Parameters generally use default values.

The following is the code to create the font:

font = (10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)

Setting the font can be done using the SetFont() method as in the following code:

(font)

The running effect is as follows:

After that we add a multiline text control to display the number of all parking spaces, the multiline text control in theCreate is to specify the style as wx.TE_MULTILINE can be, the following code:

  1. # Create a text box, specify style wx.TE_MULTILINE for multi-line text and wx.TE_READONLY for read-only.
  2. self.every_no_text = (panel, -1, pos=(30, 295), size=(220, 220),
  3. style=wx.TE_MULTILINE | wx.TE_READONLY)

The results of the run are as follows:

The above is the complete GUI interface, the overall framework we are considered to have completed the creation of the next is that we do the corresponding user events related to the code, otherwise we have no way to use this window file. The following is the complete code of the GUI interface in front of us, which can be used for research and study:

  1. import wx # Import wxpython modules
  2. class MyFrame(): # Define a subclass to give us more control over the content and appearance of the window.
  3. def __init__(self): # Define initialization methods
  4. # Set the title and size of the frame
  5. .__init__(self, None, -1, title='Calculate the number of parking spaces applet', size=(300, 600),
  6. style= | wx.CLOSE_BOX)
  7. # Add the canvas, the canvas is the container for all controls, we add text boxes, buttons and other controls are laid out on the canvas
  8. panel = (self, -1)
  9. # Add static text, set parent container to panel, ID value to -1, display text content and position
  10. (panel, -1, 'Please enter the starting parking space number', pos=(30, 30))
  11. (panel, -1, 'Please enter the termination parking space number', pos=(30, 60))
  12. (panel, -1, 'Enter the digits not included in the number, separated by commas', pos=(30, 90))
  13. (panel, -1, 'Enter the digits to be skipped in the number, separated by commas', pos=(30, 150))
  14. (panel, -1, 'The total number of parking spaces is', pos=(30, 240))
  15. (panel, -1, 'The specific car park numbers for each car park are as follows', pos=(30, 270))
  16. # Add input text box, set parent container to panel, ID value to -1, default text content, position and size
  17. self.start_no_text = (panel, -1, '001', pos=(150, 25), size=(100, -1))
  18. self.end_no_text = (panel, -1, pos=(150, 55), size=(100, -1))
  19. self.not_in_no_text = (panel, -1, pos=(30, 115), size=(220, -1))
  20. self.pass_no_text = (panel, -1, pos=(30, 175), size=(220, -1))
  21. self.total_no_text = (panel, -1, pos=(150, 235), size=(100, -1))
  22. # Create a text box, specify style wx.TE_MULTILINE for multi-line text and wx.TE_READONLY for read-only.
  23. self.every_no_text = (panel, -1, pos=(30, 295), size=(220, 220),
  24. style=wx.TE_MULTILINE | wx.TE_READONLY)
  25. # Create fonts
  26. font = (10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
  27. # Add a button control to the panel
  28. = (panel, -1, 'Click me for calculations', pos=(30, 205), size=(220, -1))
  29. # Set the font
  30. (font)

⑤ Write logic code

Due to the fact that in a chapterA small program written in Python to calculate the number of parking spaces skipped with a specific number and packaged as an executable using wxPython to make a GUI interface (Part1)Already in the python environment can perfectly realize the function we want, so most of the code can be used directly. In wxPython controls you can use the GetValue() method if you want to get the text content of the control, and the SetValue() method if you want to set the text content. This corresponds to the input function and the print() function from the previous chapter.

First we have to bind the click event method to the button first, as in the following code:

(wx.EVT_BUTTON, , )

We also need to define the click event method, this method within our main code, most of the code is directly pasted from the previous chapter, just in individual places to adapt the following code:

  1. def OnClick(self, event):
  2. # Get the data entered by the user
  3. start_no = self.start_no_text.GetValue()
  4. end_no = self.end_no_text.GetValue()
  5. pass_no = self.pass_no_text.GetValue()
  6. not_in_no = self.not_in_no_text.GetValue()
  7. # Create an empty list to store the parking space numbers
  8. parking_no_lst = []
  9. # Create an empty list for storing not_in_no
  10. not_in_no_lst = []
  11. # Separate comma-separated user-entered data into separate lists
  12. if not_in_no != "": # Add this if statement to determine that the following code will be executed only if there is data in not_in_no
  13. for item in not_in_no.replace(",", ",").split(","):
  14. not_in_no_lst.append(item)
  15. # Create an empty list to store the pass_no
  16. pass_no_lst = []
  17. # Separate comma-separated user-entered data into separate lists
  18. if pass_no != "": # Add this if statement to determine that the following code will be executed only if there is data in pass_no
  19. for item in pass_no.replace(",", ",").split(','):
  20. pass_no_lst.append(item)
  21. # Get the length of the parking space entered by the user
  22. l = len(start_no)
  23. # Iterate through all the digits from the start to the end with a for sequence.
  24. # As the input function to obtain the data format for the string format, so you need to use the int () function to convert to integer type
  25. for i in range(int(start_no), int(end_no) + 1):
  26. # Judgment
  27. if self.is_lst_in_str(not_in_no_lst, str(i)) or self.is_no_in_lst(str(i), pass_no_lst):
  28. continue
  29. else:
  30. parking_no_lst.append("0" * (l - len(str(i))) + str(i))
  31. # Calculate the length of the list with the len function to get the total number of parking spaces, and use the SetValue method to set the display text of the total_no_text control.
  32. self.total_no_text.SetValue(str(len(parking_no_lst)))
  33. # Output all parking space numbers
  34. self.every_no_text.Clear() # Empty the contents first
  35. for i in range(len(parking_no_lst) - 1):
  36. self.every_no_text.AppendText(parking_no_lst[i] + ',')
  37. self.every_no_text.AppendText(parking_no_lst[-1])
  38. def is_no_in_lst(self, no, lst):
  39. if no in lst:
  40. return True
  41. else:
  42. return False
  43. # Define a function that determines whether an element in a list is in a string or not
  44. def is_lst_in_str(self, lst, input_str):
  45. for item in lst:
  46. if item in input_str:
  47. return True
  48. return False

The code runs as follows, if you do not enter the contents of the jump sign will not report an error, but also can run correctly:

Finally there is the validation of the input to match the format we require, which requires the use of the validator in wxPython (Validator), the validator (Validator) belongs to the higher-order usage, this article will not expand the description, please research on their own. Here is the complete code.

  1. import wx # Import wxpython modules
  2. class MyFrame(): # Define a subclass to give us more control over the content and appearance of the window.
  3. def __init__(self): # Define initialization methods
  4. # Set the title and size of the frame
  5. .__init__(self, None, -1, title='Calculate the number of parking spaces applet', size=(300, 600),
  6. style= | wx.CLOSE_BOX)
  7. # Add the canvas, the canvas is the container for all controls, we add text boxes, buttons and other controls are laid out on the canvas
  8. panel = (self, -1)
  9. # Create fonts
  10. font = (10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)
  11. # Add static text, set parent container to panel, ID value to -1, display text content and position
  12. (panel, -1, 'Please enter the starting parking space number', pos=(30, 30))
  13. (panel, -1, 'Please enter the termination parking space number', pos=(30, 60))
  14. (panel, -1, 'Enter the digits not included in the number, separated by commas', pos=(30, 90))
  15. (panel, -1, 'Enter the digits to be skipped in the number, separated by commas', pos=(30, 150))
  16. (panel, -1, 'The total number of parking spaces is', pos=(30, 240))
  17. (panel, -1, 'The specific car park numbers for each car park are as follows', pos=(30, 270))
  18. # Add input text box, set parent container as panel, ID value as -1, default text content, position and size
  19. self.start_no_text = (panel, -1, '001', pos=(150, 25), size=(100, -1))
  20. self.end_no_text = (panel, -1, pos=(150, 55), size=(100, -1))
  21. self.not_in_no_text = (panel, -1, pos=(30, 115), size=(220, -1))
  22. self.pass_no_text = (panel, -1, pos=(30, 175), size=(220, -1))
  23. self.total_no_text = (panel, -1, pos=(150, 235), size=(100, -1))
  24. self.total_no_text.SetFont(font)
  25. # Create a text box, specify style wx.TE_MULTILINE for multi-line text and wx.TE_READONLY for read-only.
  26. self.every_no_text = (panel, -1, pos=(30, 295), size=(240, 220),
  27. style=wx.TE_MULTILINE | wx.TE_READONLY)
  28. # Add a button control to the panel
  29. = (panel, -1, 'Click me for calculations', pos=(30, 205), size=(220, -1))
  30. # Set the font
  31. (font)
  32. # Bind events to buttons
  33. (wx.EVT_BUTTON, , )
  34. # Define event methods
  35. def OnClick(self, event):
  36. # Get the data entered by the user
  37. start_no = self.start_no_text.GetValue()
  38. end_no = self.end_no_text.GetValue()
  39. pass_no = self.pass_no_text.GetValue()
  40. not_in_no = self.not_in_no_text.GetValue()
  41. # Create an empty list to store the parking space numbers
  42. parking_no_lst = []
  43. # Create an empty list for storing not_in_no
  44. not_in_no_lst = []
  45. # Separate comma-separated user-entered data into separate lists
  46. if not_in_no != "": # Add this if statement to determine that the following code will be executed only if there is data in not_in_no
  47. for item in not_in_no.replace(",", ",").split(","):
  48. not_in_no_lst.append(item)
  49. # Create an empty list to store the pass_no
  50. pass_no_lst = []
  51. # Separate comma-separated user-entered data into separate lists
  52. if pass_no != "": # Add this if statement to determine that the following code will be executed only if there is data in pass_no
  53. for item in pass_no.replace(",", ",").split(','):
  54. pass_no_lst.append(item)
  55. # Get the length of the parking space entered by the user
  56. l = len(start_no)
  57. # Iterate through all the digits from the start to the end with a for sequence.
  58. # As the input function to obtain the data format for the string format, so you need to use the int () function to convert to integer type
  59. for i in range(int(start_no), int(end_no) + 1):
  60. # Judgment
  61. if self.is_lst_in_str(not_in_no_lst, str(i)) or self.is_no_in_lst(str(i), pass_no_lst):
  62. continue
  63. else:
  64. parking_no_lst.append("0" * (l - len(str(i))) + str(i))
  65. # Calculate the length of the list with the len function to get the total number of parking spaces, and use the SetValue method to set the display text of the total_no_text control.
  66. self.total_no_text.SetValue(str(len(parking_no_lst)))
  67. # Output all parking space numbers
  68. self.every_no_text.Clear() # Empty the contents first
  69. for i in range(len(parking_no_lst) - 1):
  70. self.every_no_text.AppendText(parking_no_lst[i] + ',')
  71. self.every_no_text.AppendText(parking_no_lst[-1])
  72. def is_no_in_lst(self, no, lst):
  73. if no in lst:
  74. return True
  75. else:
  76. return False
  77. # Define a function that determines if an element in a list is in the string
  78. def is_lst_in_str(self, lst, input_str):
  79. for item in lst:
  80. if item in input_str:
  81. return True
  82. return False
  83. if __name__ == '__main__': # Run as main program
  84. app = () # Create an application instance
  85. frame = MyFrame() # Example of creating a window
  86. () # Make the window visible
  87. () # Call the MainLoop() method of the application instance to enter the main event loop

⑥pyinstaller to package and generate exe file

Finally, we can use pyinstaller to package the exe file in thepycharmof the control terminal can be generated with the following code:

Pyinstaller -F -w Calculate the number of parking spaces applet.py

Note that Pyinstaller is a third-party library and needs to be pip installed in advance.

Finally we will get an exe file as below, I have uploaded the file as well, if you need it please download it yourself.

3. Summary

This updated blog post is divided into two articles, but each is more than 10,000 words, this gadget implements a very simple function, but allows people to follow this article from scratch step by step to complete the entire code. I hope to bring some help to the readers.