import wx
def SingleChoiceGetDialog(wnd, ItemNameList, dlgTitle = "", hintString = ""):
"""\
SingleChoiceGetDialog(wnd, ItemNameList, dlgTitle = "", hintString = "")
Get selected index in given items.
Parameters:
wnd ( type = parent window )
ItemNameList ( type = list of string )
dlgTitle ( type = string )
hintString ( type = string )
Returns:
selectedIndex( type = int or None )"""
dlg = wx.SingleChoiceDialog(
wnd, hintString, dlgTitle,
ItemNameList,
wx.CHOICEDLG_STYLE
)
if dlg.ShowModal() == wx.ID_OK:
selectedIndex = dlg.GetSelection()
else: selectedIndex = None
dlg.Destroy()
return selectedIndex
def FilePathGet(wnd, op, wildcard, dlgTitle):
wildcard = "|".join(["""%s file (*.%s)|*.%s"""%(fileType, subName, subName)
for (fileType, subName) in wildcard])
style = (wx.SAVE | wx.CHANGE_DIR) if op == "save" else (wx.OPEN | wx.CHANGE_DIR)
FileDlg = wx.FileDialog( wnd, dlgTitle,
defaultDir="",
defaultFile="",
wildcard = wildcard,
style=style
)
if( FileDlg.ShowModal() == wx.ID_OK ):
filePath = FileDlg.GetPath()
else: filePath = None
FileDlg.Destroy()
return filePath
def FileOpenPathGetDialog(wnd, wildcard = [("All","*")], dlgTitle = "File Open"):
"""\
FileOpenPathGetDialog(wnd, wildcard = [("All","*")], dlgTitle = "File Open")
Get selected file path on action of "FileOpen".
Parameters:
wnd ( type = parent window )
wildcard ( type = list of tuple )
dlgTitle ( type = string )
Returns:
filePath ( type = string or None)"""
return FilePathGet(wnd, "open", wildcard, dlgTitle)
def FileSavePathGetDialog(wnd, wildcard = [("All","*")], dlgTitle = "File Save"):
"""\
FileSavePathGetDialog(wnd, wildcard = [("All","*")], dlgTitle = "File Save")
Get selected file path on action of "FileSave".
Parameters:
wnd ( type = parent window )
wildcard ( type = list of tuple )
dlgTitle ( type = string )
Returns:
filePath ( type = string or None )"""
return FilePathGet(wnd, "save", wildcard, dlgTitle)
def ErrorMessageDialog(wnd, msg):
"""\
ErrorMessageDialog(wnd, msg)
Popup an error message.
Parameters:
wnd ( type = parent window )
msg ( type = string )"""
dlg = wx.MessageDialog(wnd, msg, "Error", wx.OK | wx.ICON_ERROR )
dlg.ShowModal()
dlg.Destroy()
SingleChoiceGetDialog:從ItemNameList中單選。
FileOpenPathGetDialog, FileSavePathGetDialog:取得"開檔"/"存檔"的檔案路徑。
想顯示副檔名為"py"的檔案("*.py"),就在加入wildcard中加入tuple ("py","py"),前一個"py"是提示字串,後一個"py"是用來過濾副檔名的字串。
ErrorMessageDialog:彈出錯誤訊息。
對於GUI,我傾向花越少時間處理越好;漂亮,獨特的外觀是不太在乎的,只要個普通的window類型的表現,能讓使用者了解的動作提示,例如一看就知道這是要開啟檔案,就足夠了。所以我用了許多預設參數簡化函數呼叫。例如在frame中開啟檔案--
filePath = FileOpenPathGetDialog(self) # "self" is frame object in this case
if filePath: data = open(filePath,"w")
沒有留言:
張貼留言