Wxpython Instance code (shopping cart)

Source: Internet
Author: User

Wxpython is a popular cross-platform GUI toolkit. You can use this to give the program a window interface.
Official website: www.wxpython.org
I didn't learn it well, so I took an example of a small project. The code is completely pasted below, the next time you do the interface can refer to this change.

Document structure

is mainly a few py files. Resources folder is the original resource, but also two pictures

Cart    │  app_main.py    │    ├─conf    │      settings.py    │      __init__.py    │    ├─resources    │      bats.ico    │      dragon.jpg    │    └─ui            list_frame.py            list_grid_table.py            login_frame.py            my_frame.py            __init__.py
Settings file

Here is not set, but put the data here, mainly to make custom interface, not even the database:

# 登录的用户名和密码ACCOUNTS = {        ‘admin‘: {‘pwd‘: ‘admin‘},        ‘root‘: {‘pwd‘: ‘123456‘},        ‘user‘: {‘pwd‘: ‘user123‘},    }# 商品列名COLUMN_NAMES = ["商品编号", "商品类别", "商品中文名", "商品英文名"]# 商品类别CATEGORY = ["食品", "酒类", "男装", "女装", "童装"]# 商品信息,商品信息有点少,最好多搞几十条PRODUCTS = [    {‘id‘: "001", ‘category‘: "食品", ‘name_cn‘: "薯片", ‘name_en‘: "ShuPian"},    {‘id‘: "002", ‘category‘: "酒类", ‘name_cn‘: "葡萄酒", ‘name_en‘: "PuTaoJiu"},    {‘id‘: "003", ‘category‘: "男装", ‘name_cn‘: "西装", ‘name_en‘: "XiZhuang"},    {‘id‘: "004", ‘category‘: "女装", ‘name_cn‘: "短裙", ‘name_en‘: "DuanQun"},    {‘id‘: "005", ‘category‘: "童装", ‘name_cn‘: "连衣裙", ‘name_en‘: "LianYiQun"},]
Startup file

Start our project by starting the file, here is the main call to create a login window and then enter the main event loop

import wxfrom ui.login_frame import LoginFramefrom ui.list_frame import ListFrameclass App(wx.App):    """启动模块"""    def OnInit(self):        """创建窗口对象"""        frame = LoginFrame()        # frame = ListFrame()  # 单独调试商品界面的时候,省的每次都要登录一下        frame.Show()        return Trueif __name__ == ‘__main__‘:    app = App()  # 实例化    app.MainLoop()  # 进入主事件循环
Window base class

First, define a base class for all windows, and define the properties common to all windows in this base class. Then each window is based on this class:

"" Defines the frame window base class "" "Import sysimport wxclass myframe (WX. Frame): Session = {} # simulates the session of the Web, preserving the data of the sessions Def __init__ (self, title, size): Super (). __init__ (Parent=none, Title=title, Size=size, style=wx. Default_frame_style ^ Wx. Maximize_box) # style is defined as the window style, specific crossing web. Https://docs.wxpython.org/wx.Frame.html#wx-frame # above the default is included in all of the following styles: # WX. Minimize_box | Wx. Maximize_box | Wx.        Resize_border | # WX. System_menu | Wx. CAPTION | Wx. Close_box | Wx. Clip_children # The above example removes one of them. The official website example is this: # style = WX. Default_frame_style & ~ (WX. Resize_border | Wx. Maximize_box) removed 2 to fix window size # set the window centered self. Center () # Set frame window content panel Self.contentpanel = wx. Panel (parent=self) # icon File ico = WX. Icon ("Resources/bats.ico", WX. Bitmap_type_ico) # Set the icon self.        SetIcon (ICO) # Sets the window size, where the same maximum and minimum values are set, that is, the window size is fixed. # Because the above window style has retained WX. Resize_border, so here's another one to make sure the size is not adjustable # This is a bit of a bad thing, is the mousePlaced at the edge of the window, it changes to the size of the window, but does not pull the window self. Setsizehints (size, size) # Binds the Close button's Click event Self. Bind (WX. Evt_close, Self.on_close) def on_close (Self, event): # Quit System self. Destroy () Sys.exit ()

The size of the fixed window here is not adjustable, but it should be the official website of the method better.
It also defines the window's icon, and the method that is called to close the window.
self.contentpanel = wx.Panel(parent=self)This property will be used at a later time

Login window

Now start to really start the window interface, first to do a simple login interface:

"" "Login Window" "" Import wxfrom ui.my_frame import myframefrom ui.list_frame import listframefrom conf import settingsclass Login Frame (myframe): accounts = settings. ACCOUNTS def __init__ (self): Super (). __init__ (title= "User Login", size= (340, 230) # Create controls in the interface username_s t = wx. Statictext (Self.contentpanel, label= "user name:") # input box before the prompt label Password_st = wx. Statictext (Self.contentpanel, label= "Password:") Self.username_txt = wx. Textctrl (self.contentpanel) # input Box Self.password_txt = WX. Textctrl (Self.contentpanel, Style=wx.te_password) # Create FlexGrid Layout Object FGS = wx. Flexgridsizer (2, 2, 20, 20) # 2 rows 2 columns, row spacing 20, column spacing of FGS. Addmany ([# below applies 3 dividers, vertically centered, horizontally right, fixed minimum size (Username_st, 1, WX.) align_center_vertical | Wx. Align_right | Wx. fixed_minsize), # Center position, size is swell (self.username_txt, 1, WX. CENTER | Wx. EXPAND), (Password_st, 1, WX. align_center_vertical | Wx. Align_right | Wx. Fixed_minsize), (self.password_tXT, 1, WX. CENTER | Wx. EXPAND]) # Sets the FlexGrid layout object FGs. Addgrowablerow (0, 1) # The first 0 refers to the first line, the weight 1 fgs. Addgrowablerow (1, 1) # The first 1 refers to the second line, the weight is 1 # above a total of 2 lines, the user name and password, is 2 lines of space is the same FGS. Addgrowablecol (0, 1) # The first column, the weight 1, is the contents of the label FGS. Addgrowablecol (1, 4) # The second column, the weight 4, is the input box, and the input box is inflated should be full # 2 columns are divided into 5 points, the first column accounted for 1/5, the second column accounted for 4/5 # Create button Object ok_btn = wx. Button (Parent=self.contentpanel, label= "OK") Cancel_btn = wx. The button (Parent=self.contentpanel, label= "Cancel") # Binds the buttons event: The event type, the bound event, the bound button self. Bind (WX. Evt_button, Self.ok_btn_onclick, ok_btn) self. Bind (WX. Evt_button, Self.cancel_btn_onclick, cancel_btn) # Create a horizontal box layout object, put the top 2 buttons box_btn = wx. Boxsizer (WX. Horizontal) # Add a Button control: center, surrounded by borders, expands. Border is the size of the border, the actual effect does not have a box, but takes up space box_btn. ADD (OK_BTN, 1, WX. CENTER | Wx. All | Wx. EXPAND, border=10) box_btn. ADD (CANCEL_BTN, 1, WX. CENTER | Wx. All | Wx. EXPAND, border=10) # Create a vertical box and put the FGs object and the Box_btn object in it Box_outeR = wx. Boxsizer (WX. VERTICAL) Box_outer. ADD (FGS,-1, WX. CENTER | Wx. All | Wx. EXPAND, border=25) # Weight is-1, is not specified # (WX. All ^ Wx. Top) This adds only 3 sides of the border, without box_outer. ADD (BOX_BTN,-1, WX. CENTER | (WX. All ^ Wx. TOP) | Wx. EXPAND, border=20) # All the above settings are complete, the following is the Set frame window content panel Self.contentpanel.SetSizer (box_outer) # Self.contentpanel Yes def ok_btn_onclick (self, event) defined in the parent class: username = Self.username_txt. GetValue () # Take out the value of the input box Password = self.password_txt.                GetValue () if username in self.accounts:if self.accounts[username].get (' pwd ') = = password:  self.session[' username ' = Username print ("login successful") # Next move to the next frame frame = Listframe () frame. Show () self. Hide () # hides login window return else:msg = "User name or password error" ELSE:MSG = "username There is no "Print (msg) dialog = WX. Messagedialog (Self, msg, "Login Failed") # Create dialog box        Dialog. ShowModal () # Displays the dialog box dialog. Destroy () # Destroy dialog box Def cancel_btn_onclick (Self, event): Self.on_close (Event)
Product List Window

This window is more complex. There is a drop-down list, you can do a filter, the following table has a picture, and click on the table cell, the contents of the window will change accordingly:

"" "Product List Window" "Import WX, wx.gridfrom ui.my_frame import myframefrom ui.list_grid_table import Listgridtablefrom conf        Import Settingsclass Listframe (myframe): def __init__ (self): Super (). __init__ (title= "Product List", size= (1000, 700)) # Shopping Cart Self.cart = {} # commodity list self.data = settings. Products # Create separator window splitter = wx. Splitterwindow (Self.contentpanel, style=wx. Sp_3dborder) # Partition The left panel of the window Self.left_panel = Self.create_left_panel (splitter) # First prepare a function, go to the function and then implement the # Partition window The right panel of the Port Self.right_panel = Self.create_right_panel (splitter) # Sets the layout of the delimited window, and calls the Splitvertically method to layout SPL Itter. Splitvertically (Self.left_panel, Self.right_panel, 630) # Set the layout of the entire window, is a vertical box layout box_outer = wx. Boxsizer (WX.        VERTICAL) # Put this box directly into the content panel, or you can put it in the end.        # But there's only one vertical box for this window, so it doesn't matter # There are other controls that are not written, but all are added to Box_splitter self.contentpanel.SetSizer (box_outer) # Add Top Object Box_outer. ADD (Self.create_top_box (), 1, Flag=wx. EXPAND | Wx. All, border=20) # Add Delimited Window object Box_outer. ADD (splitter, 1, flag=wx. EXPAND | Wx. All, border=10) # creates the bottom status bar self. Createstatusbar () self. Setstatustext ("Ready, welcome:%s"% self.session[' username ']) def create_top_box (self): "" "Create the top layout manager" "# Create a static Text Label_st = wx. Statictext (Parent=self.contentpanel, label= "SELECT product Category:", Style=wx.        Align_right) # Creates a drop-down list object, which takes a name, which can then be found through the name of the control to get inside the content # Find the method with Findwindowbyname, also can Byid and Bylabel Choice = WX. Choice (Self.contentpanel, choices=settings. CATEGORY, name= "Choice") # Create button Object search_btn = wx. Button (Parent=self.contentpanel, label= "Query") reset_btn = wx. The button (Parent=self.contentpanel, label= "reset") # binds the event self. Bind (WX. Evt_button, Self.search_btn_onclick, search_btn) self. Bind (WX. Evt_button, Self.reset_btn_onclick, reset_btn) # Create a layout manager and add the above controls to box = WX. Boxsizer (WX. Horizontal) box. Addspacer (200) #Add a blank box. ADD (Label_st, 1, flag=wx. Fixed_minsize | Wx. All, border=10) box. ADD (choice, 1, flag=wx. Fixed_minsize | Wx. All, border=5) box. ADD (SEARCH_BTN, 1, flag=wx. Fixed_minsize | Wx. All, border=5) box. ADD (RESET_BTN, 1, flag=wx. Fixed_minsize | Wx. All, border=5) box. Addspacer (300) # Add blank return box def create_left_panel (self, parent): "" creates the left panel of the splitter window "" Panel = W X.panel (parent) # Create mesh Object Grid = Wx.grid.Grid (Panel, name= ' grid ') # Bind event self. Bind (Wx.grid.EVT_GRID_LABEL_LEFT_CLICK, Self.select_row_handler) self.        Bind (Wx.grid.EVT_GRID_CELL_LEFT_CLICK, Self.select_row_handler) # Initialize the grid self.init_grid () # or go to another function to implement # Create a Horizontal box layout manager box = WX. Boxsizer () # Sets the Grid box for box. Add (grid, 1, flag=wx. All, border=5) panel. Setsizer (box) return panel def Init_grid (self): "" "Initialize Mesh Object" "" # Gets the grid name to object Grid = self.    Findwindowbyname (' grid ')    # to create the desired table in the grid, the table here is a class table = Listgridtable (settings. Column_names, Self.data) # Sets the grid's table Properties grid. settable (table, True) # Gets the information object for the grid row, 40 is the row height, each row is 40, and the following list is specified individually for each row, here is the empty list row_size_info = Wx.grid.GridSizesInfo (40, []) # Sets the grid's row height grid. Setrowsizes (row_size_info) # Specifies the column width, preceded by 0, which specifies the column width of each column Col_size_info = wx.grid.GridSizesInfo (0, [100, 80, 130, ]) grid. Setcolsizes (Col_size_info) # Sets the cell default font grid. Setdefaultcellfont (WX. Font (one, WX. Fontfamily_default, WX. Fontstyle_normal, WX. Fontweight_normal, facename= "Microsoft Jas Black") # Sets the default font grid for table headings. Setlabelfont (WX. Font (one, WX. Fontfamily_default, WX. Fontstyle_normal, WX. Fontweight_normal, facename= "Microsoft Jas Black") # Set grid selection mode for row selection mode grid. SetselectioNmode (grid.wxgridselectrows) # Setting the grid cannot be changed by dragging the height and width grid. Disabledragrowsize () grid. Disabledragcolsize () def create_right_panel (self, parent): "" creates the right panel of the splitter window "" panel = WX. Panel (parent, style=wx. Tab_traversal | Wx. border_double) panel. Setbackgroundcolour (WX. White) # Set the background color, default is not the Black # show Picture Img_path = "resources/dragon.jpg" img = wx. Bitmap (Img_path, WX. Bitmap_type_any) # The second parameter sets the picture format can be any img_bitmap = wx. Staticbitmap (panel, bitmap=img, name= ' Img_bitmap ') # Commodity category Category = "Product Category:" Item not selected "" Category_st = WX . Statictext (panel, label=category, name= ' category ') # Create control and specify label # product name name = "Product Name:" Not yet selected "Nam E_st = wx. Statictext (panel, label=name, name= ' name ') # Price of goods = "Commodity Price: ¥{0:.2f}". Format (+) Price_st = Wx.s  Tatictext (panel, Label=price, name= ' price ') # Product Description Description = "Product Description:%s"% "very good" description_st = WX. Statictext (Panel, LabEl=description, name= ' description ') # Creates a button object add_btn = wx. button (panel, label= "Add to Cart") see_btn = wx. button (panel, label= "View shopping cart") self. Bind (WX. Evt_button, Self.add_btn_onclick, add_btn) self. Bind (WX. Evt_button, Self.see_btn_onclick, see_btn) # Layout, Vertical box layout manager box = WX. Boxsizer (WX. VERTICAL) box. ADD (Img_bitmap, 1, flag=wx. CENTER | Wx. All, border=30) box. ADD (Category_st, 1, flag=wx. EXPAND | Wx. All, border=10) box. ADD (Name_st, 1, flag=wx. EXPAND | Wx. All, border=10) box. ADD (Price_st, 1, flag=wx. EXPAND | Wx. All, border=10) box. ADD (Description_st, 1, flag=wx. EXPAND | Wx. All, border=10) box. ADD (ADD_BTN, 1, flag=wx. EXPAND | Wx. All, border=10) box. ADD (SEE_BTN, 1, flag=wx. EXPAND | Wx. All, border=10) panel. Setsizer (box) return panel def search_btn_onclick (Self, event): "" Query button can be filtered by product category "" "Choice = Sel F.findwindowbyname (' Choice ') selected = choice.  GetSelection ()      If selected >= 0:category = settings. Category[selected] # Search by product category Product = [] for item in Settings. Products:if item.get (' category ') = = Category:products.append (item) # above has been generated A new list of items, after updating the list of items, reinitialize the grid Self.data = Products Self.init_grid () def reset_btn_onclick (self, event) : "" "Click the reset button to query all items/Get the initial list of items and initialize the grid" "" Self.data = settings.        Product Self.init_grid () def select_row_handler (Self, event): "" "The row event handling of the selected grid will refresh the category and name of the right panel "" "row_selected = event. GetRow () if row_selected >= 0:selected_data = self.data[row_selected] # product Category C ategory = "Product Category:%s"% selected_data.get (' category ') Category_st = self. Findwindowbyname (' category ') Category_st. Setlabeltext (category) # First create a good control, then modify or set the Label # product name = "ProductName:%s "% selected_data.get (' name_cn ') Name_st = self. Findwindowbyname (' name ') Name_st. Setlabeltext (name) # Refresh the layout, if the replacement of the picture should be to refresh, do not change the picture without refreshing # Self.right_panel. Layout () event. Skip () # event skipped, it seems there's nothing to use Def add_btn_onclick (self, event): Pass Def see_btn_onclick (self, event): Pass
Table Object

The contents of the table displayed in the window are then implemented separately in the data table class. This inherits the Gridtablebase class, and then reconstructs several of these methods to return the table's number of rows, columns, and contents of the cell, which can be displayed in the table of the window:

"""自定义数据表格类"""from wx.grid import GridTableBaseclass ListGridTable(GridTableBase):    """自定义表格类    下面分别重构了4个方法    返回行数、列数、每个单元格的内容、列标题    """    def __init__(self, column_names, data):        super().__init__()        self.col_labels = column_names        self.data = data    def GetNumberRows(self):        return len(self.data)    def GetNumberCols(self):        return len(self.col_labels)    def GetValue(self, row, col):        products = self.data[row]        return {            0: products.get(‘id‘),            1: products.get(‘category‘),            2: products.get(‘name_cn‘),            3: products.get(‘name_en‘),        }.get(col)    def GetColLabelValue(self, col):        return self.col_labels[col]
Effect

Login window

Product List Window

Wxpython Instance code (shopping cart)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.