1. Requirements Description
Create a main form
Place a menu bar on a form
Place a drop-down menu in the menu bar
Put a menu item in the drop-down menu
Bind a Click event to a menu item, open the File Selection dialog box in the Click event, get the Select file name
2. Code
1 ImportWX2 ImportFileinput3 4 classFrmmain (WX. Frame):5App =WX. APP ()6MenuBar =None7Filemenu =None8Openmenuitem =None9FileDialog =NoneTen One def __init__(Self, *args): ASuper (Frmmain, self).__init__(*args) -Self.menubar =WX. MenuBar () -Self.filemenu =WX. Menu () theSelf.openmenuitem = wx. MenuItem (Self.filemenu, 1,'&open. \tctrl+o') - self.fileMenu.Append (Self.openmenuitem) -Self.menuBar.Append (Self.filemenu, title="File") - Self . Setmenubar (Self.menubar) +Self.filedialog = wx. FileDialog (Self,"Open File", wildcard="files (*.html) |*.html", Style=wx. Fd_open |WX. Fd_file_must_exist) - Self . Bind (WX. Evt_menu, Self.menu_click) +Self. SetSize ((300,400)) A Self . Center () at Self . Show () - Self.app.MainLoop () - - defMenu_click (Self, event): - ifSelf.fileDialog.ShowModal () = =Wx.id_cancel: - return inpathname =Self.fileDialog.GetPath () - Try: to With fileinput.input (pathname) as file: +line =File.readline () - Print(line) the exceptIOError: *Wx. LogError ("cannot open file '%s '."% pathname)
3. Row by line explanation
Line 4th: The main form class inherits WX. Frame
第6-9 Line:
- MenuBar Form class Member menu bar control
- Filemanu Form class Member drop-down menu control
- Openmenuitem Form class Member menu item control
- FileDialog Form Class Member file dialog box control
Line 11th: constructor, you must add the parameter *agrs, otherwise the form cannot be instantiated.
Line 12th: The constructor of the base class must be called, otherwise the form cannot be instantiated.
第13-22 Line:
Instantiating the menu bar
Instantiate drop-down menu
Instantiate a menu item
To add a menu item to the drop-down menu
Add a drop-down menu to the menu bar
Add a menu bar to a form
Instantiate file dialog box: Wildcard represents the file name extension that restricts the selection,
First WxPython form Application