diff --git a/gui/builtinItemStatsViews/itemAttributes.py b/gui/builtinItemStatsViews/itemAttributes.py index f36fae0f7..e0d58f781 100644 --- a/gui/builtinItemStatsViews/itemAttributes.py +++ b/gui/builtinItemStatsViews/itemAttributes.py @@ -108,62 +108,64 @@ class ItemParams(wx.Panel): def ExportItemStats(self, event): exportFileName = self.item.name + " (" + str(self.item.ID) + ").csv" - saveFileDialog = wx.FileDialog(self, "Save CSV file", "", exportFileName, - "CSV files (*.csv)|*.csv", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) + with wx.FileDialog( + self, "Save CSV file", "", exportFileName, + "CSV files (*.csv)|*.csv", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT + ) as dlg: - if saveFileDialog.ShowModal() == wx.ID_CANCEL: - return # the user hit cancel... + if dlg.ShowModal() == wx.ID_CANCEL: + return # the user hit cancel... - with open(saveFileDialog.GetPath(), "w") as exportFile: - writer = csv.writer(exportFile, delimiter=',') - - writer.writerow( - [ - "ID", - "Internal Name", - "Friendly Name", - "Modified Value", - "Base Value", - ] - ) - - for attribute in self.attrValues: - - try: - attribute_id = self.attrInfo[attribute].ID - except (KeyError, AttributeError): - attribute_id = '' - - try: - attribute_name = self.attrInfo[attribute].name - except (KeyError, AttributeError): - attribute_name = attribute - - try: - attribute_displayname = self.attrInfo[attribute].displayName - except (KeyError, AttributeError): - attribute_displayname = '' - - try: - attribute_value = self.attrInfo[attribute].value - except (KeyError, AttributeError): - attribute_value = '' - - try: - attribute_modified_value = self.attrValues[attribute].value - except (KeyError, AttributeError): - attribute_modified_value = self.attrValues[attribute] + with open(dlg.GetPath(), "w") as exportFile: + writer = csv.writer(exportFile, delimiter=',') writer.writerow( [ - attribute_id, - attribute_name, - attribute_displayname, - attribute_modified_value, - attribute_value, + "ID", + "Internal Name", + "Friendly Name", + "Modified Value", + "Base Value", ] ) + for attribute in self.attrValues: + + try: + attribute_id = self.attrInfo[attribute].ID + except (KeyError, AttributeError): + attribute_id = '' + + try: + attribute_name = self.attrInfo[attribute].name + except (KeyError, AttributeError): + attribute_name = attribute + + try: + attribute_displayname = self.attrInfo[attribute].displayName + except (KeyError, AttributeError): + attribute_displayname = '' + + try: + attribute_value = self.attrInfo[attribute].value + except (KeyError, AttributeError): + attribute_value = '' + + try: + attribute_modified_value = self.attrValues[attribute].value + except (KeyError, AttributeError): + attribute_modified_value = self.attrValues[attribute] + + writer.writerow( + [ + attribute_id, + attribute_name, + attribute_displayname, + attribute_modified_value, + attribute_value, + ] + ) + def SetupImageList(self): self.imageList.RemoveAll() diff --git a/gui/builtinShipBrowser/fitItem.py b/gui/builtinShipBrowser/fitItem.py index e6981c78f..300223926 100644 --- a/gui/builtinShipBrowser/fitItem.py +++ b/gui/builtinShipBrowser/fitItem.py @@ -344,15 +344,14 @@ class FitItem(SFItem.SFBrowserItem): if mstate.GetModifiers() == wx.MOD_SHIFT or mstate.MiddleIsDown(): self.deleteFit() else: - dlg = wx.MessageDialog( + with wx.MessageDialog( self, "Do you really want to delete this fit?", "Confirm Delete", wx.YES | wx.NO | wx.ICON_QUESTION - ) - - if dlg.ShowModal() == wx.ID_YES: - self.deleteFit() + ) as dlg: + if dlg.ShowModal() == wx.ID_YES: + self.deleteFit() def deleteFit(self, event=None): pyfalog.debug("Deleting ship fit.") diff --git a/gui/characterEditor.py b/gui/characterEditor.py index 2a462d680..7b272d97f 100644 --- a/gui/characterEditor.py +++ b/gui/characterEditor.py @@ -305,16 +305,18 @@ class CharacterEditor(wx.Frame): sChar = Character.getInstance() name = sChar.getCharName(charID) - dlg = TextEntryValidatedDialog(parent, CharacterTextValidor, - "Enter a name for your new Character:", - "Save Character As...") - dlg.SetValue("{} Copy".format(name)) - dlg.txtctrl.SetInsertionPointEnd() - dlg.CenterOnParent() + with TextEntryValidatedDialog( + parent, CharacterTextValidor, + "Enter a name for your new Character:", + "Save Character As..." + ) as dlg: + dlg.SetValue("{} Copy".format(name)) + dlg.txtctrl.SetInsertionPointEnd() + dlg.CenterOnParent() - if dlg.ShowModal() == wx.ID_OK: - sChar = Character.getInstance() - return sChar.saveCharacterAs(charID, dlg.txtctrl.GetValue().strip()) + if dlg.ShowModal() == wx.ID_OK: + sChar = Character.getInstance() + return sChar.saveCharacterAs(charID, dlg.txtctrl.GetValue().strip()) class SkillTreeView(wx.Panel): @@ -436,11 +438,12 @@ class SkillTreeView(wx.Panel): def importSkills(self, evt): - dlg = wx.MessageDialog(self, "Importing skills into this character will set the skill levels as pending. " + - "To save the skills permanently, please click the Save button at the bottom of the window after importing" - , "Import Skills", wx.OK) - dlg.ShowModal() - dlg.Destroy() + with wx.MessageDialog( + self, ("Importing skills into this character will set the skill levels as pending. To save the skills " + "permanently, please click the Save button at the bottom of the window after importing"), + "Import Skills", wx.OK + ) as dlg: + dlg.ShowModal() text = fromClipboard().strip() if text: @@ -456,10 +459,9 @@ class SkillTreeView(wx.Panel): skill.setLevel(level, ignoreRestrict=True) except Exception as e: - dlg = wx.MessageDialog(self, "There was an error importing skills, please see log file", "Error", wx.ICON_ERROR) - dlg.ShowModal() - dlg.Destroy() pyfalog.error(e) + with wx.MessageDialog(self, "There was an error importing skills, please see log file", "Error", wx.ICON_ERROR) as dlg: + dlg.ShowModal() finally: self.charEditor.btnRestrict() diff --git a/gui/esiFittings.py b/gui/esiFittings.py index d58734a1a..99c29e064 100644 --- a/gui/esiFittings.py +++ b/gui/esiFittings.py @@ -149,45 +149,50 @@ class EveFittings(wx.Frame): return data = json.loads(self.fitTree.fittingsTreeCtrl.GetItemData(selection)) - dlg = wx.MessageDialog(self, - "Do you really want to delete %s (%s) from EVE?" % (data['name'], getItem(data['ship_type_id']).name), - "Confirm Delete", wx.YES | wx.NO | wx.ICON_QUESTION) - - if dlg.ShowModal() == wx.ID_YES: - try: - sEsi.delFitting(self.getActiveCharacter(), data['fitting_id']) - # repopulate the fitting list - self.fitTree.populateSkillTree(self.fittings) - self.fitView.update([]) - except requests.exceptions.ConnectionError: - msg = "Connection error, please check your internet connection" - pyfalog.error(msg) - self.statusbar.SetStatusText(msg) + with wx.MessageDialog( + self, "Do you really want to delete %s (%s) from EVE?" % (data['name'], getItem(data['ship_type_id']).name), + "Confirm Delete", wx.YES | wx.NO | wx.ICON_QUESTION + ) as dlg: + if dlg.ShowModal() == wx.ID_YES: + try: + sEsi.delFitting(self.getActiveCharacter(), data['fitting_id']) + # repopulate the fitting list + self.fitTree.populateSkillTree(self.fittings) + self.fitView.update([]) + except requests.exceptions.ConnectionError: + msg = "Connection error, please check your internet connection" + pyfalog.error(msg) + self.statusbar.SetStatusText(msg) class ESIServerExceptionHandler: def __init__(self, parentWindow, ex): - dlg = wx.MessageDialog(parentWindow, - "There was an issue starting up the localized server, try setting " - "Login Authentication Method to Manual by going to Preferences -> EVE SS0 -> " - "Login Authentication Method. If this doesn't fix the problem please file an " - "issue on Github.", - "Add Character Error", - wx.OK | wx.ICON_ERROR) - dlg.ShowModal() pyfalog.error(ex) + with wx.MessageDialog( + parentWindow, + "There was an issue starting up the localized server, try setting " + "Login Authentication Method to Manual by going to Preferences -> EVE SS0 -> " + "Login Authentication Method. If this doesn't fix the problem please file an " + "issue on Github.", + "Add Character Error", + wx.OK | wx.ICON_ERROR + ) as dlg: + dlg.ShowModal() class ESIExceptionHandler: # todo: make this a generate excetpion handler for all calls def __init__(self, parentWindow, ex): if ex.response['error'].startswith('Token is not valid') or ex.response['error'] == 'invalid_token': # todo: this seems messy, figure out a better response - dlg = wx.MessageDialog(parentWindow, - "There was an error validating characters' SSO token. Please try " - "logging into the character again to reset the token.", "Invalid Token", - wx.OK | wx.ICON_ERROR) - dlg.ShowModal() pyfalog.error(ex) + with wx.MessageDialog( + parentWindow, + "There was an error validating characters' SSO token. Please try " + "logging into the character again to reset the token.", + "Invalid Token", + wx.OK | wx.ICON_ERROR + ) as dlg: + dlg.ShowModal() else: # We don't know how to handle the error, raise it for the global error handler to pick it up raise ex diff --git a/gui/mainFrame.py b/gui/mainFrame.py index aa018997c..627494f08 100644 --- a/gui/mainFrame.py +++ b/gui/mainFrame.py @@ -424,29 +424,31 @@ class MainFrame(wx.Frame): fit = sFit.getFit(self.getActiveFit()) defaultFile = "%s - %s.xml" % (fit.ship.item.name, fit.name) if fit else None - dlg = wx.FileDialog(self, "Save Fitting As...", - wildcard="EVE XML fitting files (*.xml)|*.xml", - style=wx.FD_SAVE, - defaultFile=defaultFile) - if dlg.ShowModal() == wx.ID_OK: - self.supress_left_up = True - format_ = dlg.GetFilterIndex() - path = dlg.GetPath() - if format_ == 0: - output = Port.exportXml([fit], None) - if '.' not in os.path.basename(path): - path += ".xml" - else: - pyfalog.warning("oops, invalid fit format %d" % format_) - try: - dlg.Destroy() - except RuntimeError: - pyfalog.error("Tried to destroy an object that doesn't exist in .") - return + with wx.FileDialog( + self, "Save Fitting As...", + wildcard="EVE XML fitting files (*.xml)|*.xml", + style=wx.FD_SAVE, + defaultFile=defaultFile + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + self.supress_left_up = True + format_ = dlg.GetFilterIndex() + path = dlg.GetPath() + if format_ == 0: + output = Port.exportXml([fit], None) + if '.' not in os.path.basename(path): + path += ".xml" + else: + pyfalog.warning("oops, invalid fit format %d" % format_) + try: + dlg.Destroy() + except RuntimeError: + pyfalog.error("Tried to destroy an object that doesn't exist in .") + return - with open(path, "w", encoding="utf-8") as openfile: - openfile.write(output) - openfile.close() + with open(path, "w", encoding="utf-8") as openfile: + openfile.write(output) + openfile.close() try: dlg.Destroy() @@ -606,13 +608,18 @@ class MainFrame(wx.Frame): fit = sFit.getFit(fitID) if not fit.ignoreRestrictions: - dlg = wx.MessageDialog(self, "Are you sure you wish to ignore fitting restrictions for the " - "current fit? This could lead to wildly inaccurate results and possible errors.", "Confirm", wx.YES_NO | wx.ICON_QUESTION) + with wx.MessageDialog( + self, "Are you sure you wish to ignore fitting restrictions for the " + "current fit? This could lead to wildly inaccurate results and possible errors.", + "Confirm", wx.YES_NO | wx.ICON_QUESTION + ) as dlg: + result = dlg.ShowModal() == wx.ID_YES else: - dlg = wx.MessageDialog(self, "Re-enabling fitting restrictions for this fit will also remove any illegal items " - "from the fit. Do you want to continue?", "Confirm", wx.YES_NO | wx.ICON_QUESTION) - result = dlg.ShowModal() == wx.ID_YES - dlg.Destroy() + with wx.MessageDialog( + self, "Re-enabling fitting restrictions for this fit will also remove any illegal items " + "from the fit. Do you want to continue?", "Confirm", wx.YES_NO | wx.ICON_QUESTION + ) as dlg: + result = dlg.ShowModal() == wx.ID_YES if result: self.command.Submit(cmd.GuiToggleFittingRestrictionsCommand(fitID=fitID)) @@ -739,88 +746,79 @@ class MainFrame(wx.Frame): def exportSkillsNeeded(self, event): """ Exports skills needed for active fit and active character """ sCharacter = Character.getInstance() - saveDialog = wx.FileDialog( + with wx.FileDialog( self, "Export Skills Needed As...", wildcard=("EVEMon skills training file (*.emp)|*.emp|" "EVEMon skills training XML file (*.xml)|*.xml|" "Text skills training file (*.txt)|*.txt"), style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, - ) + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + saveFmtInt = dlg.GetFilterIndex() - if saveDialog.ShowModal() == wx.ID_OK: - saveFmtInt = saveDialog.GetFilterIndex() + if saveFmtInt == 0: # Per ordering of wildcards above + saveFmt = "emp" + elif saveFmtInt == 1: + saveFmt = "xml" + else: + saveFmt = "txt" - if saveFmtInt == 0: # Per ordering of wildcards above - saveFmt = "emp" - elif saveFmtInt == 1: - saveFmt = "xml" - else: - saveFmt = "txt" + filePath = dlg.GetPath() + if '.' not in os.path.basename(filePath): + filePath += ".{0}".format(saveFmt) - filePath = saveDialog.GetPath() - if '.' not in os.path.basename(filePath): - filePath += ".{0}".format(saveFmt) - - self.waitDialog = wx.BusyInfo("Exporting skills needed...") - sCharacter.backupSkills(filePath, saveFmt, self.getActiveFit(), self.closeWaitDialog) - - saveDialog.Destroy() + self.waitDialog = wx.BusyInfo("Exporting skills needed...") + sCharacter.backupSkills(filePath, saveFmt, self.getActiveFit(), self.closeWaitDialog) def fileImportDialog(self, event): """Handles importing single/multiple EVE XML / EFT cfg fit files""" - dlg = wx.FileDialog( + with wx.FileDialog( self, "Open One Or More Fitting Files", wildcard=("EVE XML fitting files (*.xml)|*.xml|" "EFT text fitting files (*.cfg)|*.cfg|" "All Files (*)|*"), style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE - ) - if dlg.ShowModal() == wx.ID_OK: - self.progressDialog = wx.ProgressDialog( - "Importing fits", - " " * 100, # set some arbitrary spacing to create width in window - parent=self, - style=wx.PD_CAN_ABORT | wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_APP_MODAL - ) - # self.progressDialog.message = None - Port.importFitsThreaded(dlg.GetPaths(), self) - self.progressDialog.ShowModal() - try: - dlg.Destroy() - except RuntimeError: - pyfalog.error("Tried to destroy an object that doesn't exist in .") + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + self.progressDialog = wx.ProgressDialog( + "Importing fits", + " " * 100, # set some arbitrary spacing to create width in window + parent=self, + style=wx.PD_CAN_ABORT | wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_APP_MODAL + ) + Port.importFitsThreaded(dlg.GetPaths(), self) + self.progressDialog.ShowModal() def backupToXml(self, event): """ Back up all fits to EVE XML file """ defaultFile = "pyfa-fits-%s.xml" % strftime("%Y%m%d_%H%M%S", gmtime()) - saveDialog = wx.FileDialog( + with wx.FileDialog( self, "Save Backup As...", wildcard="EVE XML fitting file (*.xml)|*.xml", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, defaultFile=defaultFile, - ) + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + filePath = dlg.GetPath() + if '.' not in os.path.basename(filePath): + filePath += ".xml" - if saveDialog.ShowModal() == wx.ID_OK: - filePath = saveDialog.GetPath() - if '.' not in os.path.basename(filePath): - filePath += ".xml" + sFit = Fit.getInstance() + max_ = sFit.countAllFits() - sFit = Fit.getInstance() - max_ = sFit.countAllFits() - - self.progressDialog = wx.ProgressDialog( - "Backup fits", - "Backing up %d fits to: %s" % (max_, filePath), - maximum=max_, - parent=self, - style=wx.PD_CAN_ABORT | wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_APP_MODAL - ) - Port.backupFits(filePath, self) - self.progressDialog.ShowModal() + self.progressDialog = wx.ProgressDialog( + "Backup fits", + "Backing up %d fits to: %s" % (max_, filePath), + maximum=max_, + parent=self, + style=wx.PD_CAN_ABORT | wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_APP_MODAL + ) + Port.backupFits(filePath, self) + self.progressDialog.ShowModal() def exportHtml(self, event): from gui.utils.exportHtml import exportHtml @@ -831,15 +829,14 @@ class MainFrame(wx.Frame): path = settings.getPath() if not os.path.isdir(os.path.dirname(path)): - dlg = wx.MessageDialog( + with wx.MessageDialog( self, "Invalid Path\n\nThe following path is invalid or does not exist: \n%s\n\nPlease verify path location pyfa's preferences." % path, "Error", wx.OK | wx.ICON_ERROR - ) - - if dlg.ShowModal() == wx.ID_OK: - return + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + return self.progressDialog = wx.ProgressDialog( "Backup fits", @@ -887,12 +884,12 @@ class MainFrame(wx.Frame): if action & IPortUser.ID_ERROR: self.closeProgressDialog() _message = "Import Error" if action & IPortUser.PROCESS_IMPORT else "Export Error" - dlg = wx.MessageDialog(self, - "The following error was generated\n\n%s\n\nBe aware that already processed fits were not saved" % data, - _message, wx.OK | wx.ICON_ERROR) - # if dlg.ShowModal() == wx.ID_OK: - # return - dlg.ShowModal() + with wx.MessageDialog( + self, + "The following error was generated\n\n%s\n\nBe aware that already processed fits were not saved" % data, + _message, wx.OK | wx.ICON_ERROR + ) as dlg: + dlg.ShowModal() return # data is str @@ -946,18 +943,17 @@ class MainFrame(wx.Frame): def importCharacter(self, event): """ Imports character XML file from EVE API """ - dlg = wx.FileDialog( + with wx.FileDialog( self, "Open One Or More Character Files", wildcard="EVE API XML character files (*.xml)|*.xml|All Files (*)|*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE - ) - - if dlg.ShowModal() == wx.ID_OK: - self.supress_left_up = True - self.waitDialog = wx.BusyInfo("Importing Character...") - sCharacter = Character.getInstance() - sCharacter.importCharacter(dlg.GetPaths(), self.importCharacterCallback) + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + self.supress_left_up = True + self.waitDialog = wx.BusyInfo("Importing Character...") + sCharacter = Character.getInstance() + sCharacter.importCharacter(dlg.GetPaths(), self.importCharacterCallback) def importCharacterCallback(self): self.closeWaitDialog() diff --git a/gui/propertyEditor.py b/gui/propertyEditor.py index d744b4580..f5eec9f02 100644 --- a/gui/propertyEditor.py +++ b/gui/propertyEditor.py @@ -110,60 +110,62 @@ class AttributeEditor(wx.Frame): self.Destroy() def OnImport(self, event): - dlg = wx.FileDialog(self, "Import pyfa override file", - wildcard="pyfa override file (*.csv)|*.csv", - style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - if dlg.ShowModal() == wx.ID_OK: - path = dlg.GetPath() - with open(path, 'r') as csvfile: - spamreader = csv.reader(csvfile) - for row in spamreader: - if len(row) == 0: # csvwriter seems to added blank lines to the end sometimes - continue - itemID, attrID, value = row - item = getItem(int(itemID)) - attr = getAttributeInfo(int(attrID)) - item.setOverride(attr, float(value)) - self.itemView.updateItems(True) + with wx.FileDialog( + self, "Import pyfa override file", + wildcard="pyfa override file (*.csv)|*.csv", + style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + path = dlg.GetPath() + with open(path, 'r') as csvfile: + spamreader = csv.reader(csvfile) + for row in spamreader: + if len(row) == 0: # csvwriter seems to added blank lines to the end sometimes + continue + itemID, attrID, value = row + item = getItem(int(itemID)) + attr = getAttributeInfo(int(attrID)) + item.setOverride(attr, float(value)) + self.itemView.updateItems(True) def OnExport(self, event): sMkt = Market.getInstance() items = sMkt.getItemsWithOverrides() defaultFile = "pyfa_overrides.csv" - dlg = wx.FileDialog(self, "Save Overrides As...", - wildcard="pyfa overrides (*.csv)|*.csv", - style=wx.FD_SAVE, - defaultFile=defaultFile) - - if dlg.ShowModal() == wx.ID_OK: - path = dlg.GetPath() - with open(path, 'w', encoding='utf-8') as csvfile: - writer = csv.writer(csvfile) - for item in items: - for key, override in item.overrides.items(): - writer.writerow([item.ID, override.attrID, override.value]) + with wx.FileDialog( + self, "Save Overrides As...", + wildcard="pyfa overrides (*.csv)|*.csv", + style=wx.FD_SAVE, + defaultFile=defaultFile + ) as dlg: + if dlg.ShowModal() == wx.ID_OK: + path = dlg.GetPath() + with open(path, 'w', encoding='utf-8') as csvfile: + writer = csv.writer(csvfile) + for item in items: + for key, override in item.overrides.items(): + writer.writerow([item.ID, override.attrID, override.value]) def OnClear(self, event): - dlg = wx.MessageDialog( + with wx.MessageDialog( self, "Are you sure you want to delete all overrides?", "Confirm Delete", wx.YES | wx.NO | wx.ICON_EXCLAMATION - ) - - if dlg.ShowModal() == wx.ID_YES: - sMkt = Market.getInstance() - items = sMkt.getItemsWithOverrides() - # We can't just delete overrides, as loaded items will still have - # them assigned. Deleting them from the database won't propagate - # them due to the eve/user database disconnect. We must loop through - # all items that have overrides and remove them - for item in items: - for _, x in list(item.overrides.items()): - item.deleteOverride(x.attr) - self.itemView.updateItems(True) - self.pg.Clear() + ) as dlg: + if dlg.ShowModal() == wx.ID_YES: + sMkt = Market.getInstance() + items = sMkt.getItemsWithOverrides() + # We can't just delete overrides, as loaded items will still have + # them assigned. Deleting them from the database won't propagate + # them due to the eve/user database disconnect. We must loop through + # all items that have overrides and remove them + for item in items: + for _, x in list(item.overrides.items()): + item.deleteOverride(x.attr) + self.itemView.updateItems(True) + self.pg.Clear() # This is literally a stripped down version of the market. diff --git a/gui/utils/helpers_wxPython.py b/gui/utils/helpers_wxPython.py index 26f98c35d..8d78b6d63 100644 --- a/gui/utils/helpers_wxPython.py +++ b/gui/utils/helpers_wxPython.py @@ -2,9 +2,8 @@ import wx def YesNoDialog(question='Are you sure you want to do this?', caption='Yes or no?'): - dlg = wx.MessageDialog(None, question, caption, wx.YES_NO | wx.ICON_QUESTION) - result = dlg.ShowModal() == wx.ID_YES - dlg.Destroy() + with wx.MessageDialog(None, question, caption, wx.YES_NO | wx.ICON_QUESTION) as dlg: + result = dlg.ShowModal() == wx.ID_YES return result @@ -25,4 +24,4 @@ def HandleCtrlBackspace(textControl): elif foundChar: break textControl.Remove(startIndex, curPos) - textControl.SetInsertionPoint(startIndex) \ No newline at end of file + textControl.SetInsertionPoint(startIndex) diff --git a/tests/test_locale/file_dialog.py b/tests/test_locale/file_dialog.py index f72dccf8c..d5c2479ff 100644 --- a/tests/test_locale/file_dialog.py +++ b/tests/test_locale/file_dialog.py @@ -31,58 +31,60 @@ class MyForm(wx.Frame): # ---------------------------------------------------------------------- def loadFile(self, event): - openFileDialog = wx.FileDialog(self, "Open", "", "", - "Python files (*.py)|*.py", - wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - openFileDialog.ShowModal() - path = openFileDialog.GetPath() - try: - os_walk_without_codec = GetPath(path) - except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: - os_walk_without_codec = e + with wx.FileDialog( + self, "Open", "", "", + "Python files (*.py)|*.py", + wx.FD_OPEN | wx.FD_FILE_MUST_EXIST + ) as dlg: + dlg.ShowModal() + path = dlg.GetPath() + try: + os_walk_without_codec = GetPath(path) + except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: + os_walk_without_codec = e - try: - os_walk_with_system_codec = GetPath(path, None, sys.getdefaultencoding()) - except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: - os_walk_with_system_codec = e + try: + os_walk_with_system_codec = GetPath(path, None, sys.getdefaultencoding()) + except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: + os_walk_with_system_codec = e - try: - os_walk_unicode_without_codec = GetUnicodePath(path) - except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: - os_walk_unicode_without_codec = e + try: + os_walk_unicode_without_codec = GetUnicodePath(path) + except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: + os_walk_unicode_without_codec = e - try: - os_walk_unicode_with_system_codec = GetUnicodePath(path, None, sys.getdefaultencoding()) - except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: - os_walk_unicode_with_system_codec = e + try: + os_walk_unicode_with_system_codec = GetUnicodePath(path, None, sys.getdefaultencoding()) + except (UnicodeEncodeError, UnicodeTranslateError, UnicodeError, UnicodeDecodeError, UnicodeWarning, TypeError) as e: + os_walk_unicode_with_system_codec = e - print("Simple print:") - print(path) + print("Simple print:") + print(path) - print("Type:") - print((type(path))) + print("Type:") + print((type(path))) - print("OS Walk: No Codec:") - print(os_walk_without_codec) + print("OS Walk: No Codec:") + print(os_walk_without_codec) - print("OS Walk: Default System Codec:") - print(os_walk_with_system_codec) + print("OS Walk: Default System Codec:") + print(os_walk_with_system_codec) - print("OS Unicode Walk: No Codec:") - print(os_walk_unicode_without_codec) + print("OS Unicode Walk: No Codec:") + print(os_walk_unicode_without_codec) - print("OS Unicode Walk: Default System Codec:") - print(os_walk_unicode_with_system_codec) - openFileDialog.Destroy() + print("OS Unicode Walk: Default System Codec:") + print(os_walk_unicode_with_system_codec) # ---------------------------------------------------------------------- def saveFile(self, event): - saveFileDialog = wx.FileDialog(self, "Save As", "", "", - "Python files (*.py)|*.py", - wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) - saveFileDialog.ShowModal() - saveFileDialog.GetPath() - saveFileDialog.Destroy() + with wx.FileDialog( + self, "Save As", "", "", + "Python files (*.py)|*.py", + wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT + ) as dlg: + dlg.ShowModal() + dlg.GetPath() # Run the program