Python GUI庫wxPython官網Hello World示例的逐行解釋

這篇文章是對wxPython官網第二個"Hello World"的demo代碼的逐行解釋,不過爲方便初學者作了小部分改動,勉強算對wxPython的入門瞭解。python

1、環境與工具

  • 本機:Windows10 64位
  • Python 3.5.2
  • wxPython 4.0.0b2
  • IDE:Pycharm Professional 2017.2.3

2、代碼解釋

# !/usr/bin/env python
# _*_ coding:utf-8 _*_

import wx
'''
frame(窗口):帶標題和邊框的最頂層窗體
panel(面板):容器類,提供空間放其餘組件,包括其餘panel
'''

class HelloFrame(wx.Frame):
    def __init__(self, *args, **kw):
        super(HelloFrame, self).__init__(*args, **kw)

        # 建立一個Panel實例
        pn1 = wx.Panel(self)
        
        # 在pn1上建立一個靜態文本組件(StaticText)
        # +label表示要顯示的文本內容
        # +pos表示文本顯示位置
        st = wx.StaticText(pn1, label="A simple wxPython demo!", pos=(25, 25))
        
        # 設置文本內容字號並粗體顯示
        font = st.GetFont()
        font.PointSize += 10
        font = font.Bold()
        st.SetFont(font)
        
        # 建立菜單欄
        self.makeMenuBar()
        # 建立狀態欄
        self.CreateStatusBar()
        # 設置狀態欄要顯示的文本內容
        self.SetStatusText("Ready to update to Hello World v3.0!")

    def makeMenuBar(self):
        # 建立菜單對象fileMenu(菜單欄主選項1)
        fileMenu = wx.Menu()
        
        # 在fileMenu中添加子項createItem
        # +item表示子項
        # +helpString表示對子項的說明,當鼠標移動到子項上時,會在狀態欄顯示
        # \t...語法容許用戶鍵盤操做觸發子項
        createItem = fileMenu.Append(wx.ID_ANY, item=u"新建文件(N)...\tCtrl-H", helpString="建立一個新的文件")
        
        # 在各子項中添加起分隔做用的橫線
        fileMenu.AppendSeparator()
        
        # 在fileMenu中添加子項exitItem
        exitItem = fileMenu.Append(wx.ID_EXIT, item=u"退出")

        # 建立菜單對象helpMenu(菜單欄主選項2)
        helpMenu = wx.Menu()
        # 在fileMenu中添加子項aboutItem
        aboutItem = helpMenu.Append(wx.ID_ABOUT, item=u"關於")

        # 建立菜單欄
        menuBar = wx.MenuBar()
        # 添加各個菜單欄主選項到菜單欄中
        # "&"後的首字母+"alt"鍵觸發菜單選項。該首字母會如下劃線着重顯示,按住alt鍵即能看見。
        menuBar.Append(fileMenu, u"文件(&F)")
        menuBar.Append(helpMenu, u"幫助(&H)")
        # 添加菜單欄到窗口
        self.SetMenuBar(menuBar)

        # 將主菜單的全部子項綁定動做
        self.Bind(wx.EVT_MENU, self.OnCreate, source=createItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, source=aboutItem)
        self.Bind(wx.EVT_MENU, self.OnExit, source=exitItem)

    def OnExit(self, event):
        # 關閉窗口
        self.Close(True)

    def OnCreate(self, event):
        wx.MessageBox(u"建立文件成功")

    def OnAbout(self, event):
        # MessageBox(message, caption=MessageBoxCaptionStr, style=OK|CENTRE, parent=None, x=DefaultCoord, y=DefaultCoord)
        # +調用message()方法將會彈出一個對話窗口
        # +message表示對話窗口顯示的正文信息
        # +caption表示對話窗口的標題
        # +style表示對話窗口的按鈕和圖標樣式
        wx.MessageBox("Hello World v2.0\r\nproducted by wxPython.",
                      "About",
                      wx.OK | wx.ICON_INFORMATION)


if __name__ == "__main__":
    app = wx.App()
    frame = HelloFrame(None, title="Hello World v2.0")
    frame.Show()
    app.MainLoop()
相關文章
相關標籤/搜索