def generate():
global sound
statement = coremeraco.constructRegularStatement() + os.linesep
textArea.insert(Tkinter.END, statement)
textArea.yview(Tkinter.END)
if readOption and readOutputState.get():
if sound:
sound.stop()
sound = playsnd.playsnd()
threading.Thread(target=sound.play, args=(procfest.text2wave(statement),)).start()
if saveOutputState.get():
try:
outputFileHandler = open(saveOutputDestination.get(), 'a') # 'a' means append mode
outputFileHandler.write(statement)
outputFileHandler.close()
except IOError as Argument:
tkMessageBox.showerror(productName, meracolocale.getLocalisedString(localisationFile, "ioErrorMessage") + str(Argument))
except Exception as Argument:
tkMessageBox.showerror(productName, meracolocale.getLocalisedString(localisationFile, "genericErrorMessage") + str(Argument))
python类showerror()的实例源码
def validate(self):
for key in self.entrydict.keys():
if key.find("Password") == -1:
self.settings[self.section][key] = self.entrydict[key].get()
else:
self.settings[self.section][key] = myutils.password_obfuscate(self.entrydict[key].get())
errortext="Some of your input contains errors. Detailed error output below.\n\n"
val = Validator()
valresult=self.settings.validate(val, preserve_errors=True)
if valresult != True:
if valresult.has_key(self.section):
sectionval = valresult[self.section]
for key in sectionval.keys():
if sectionval[key] != True:
errortext += "Error in item \"" + str(key) + "\": " + str(sectionval[key]) + "\n"
tkMessageBox.showerror("Erroneous input. Please try again.", errortext)
return 0
else:
return 1
def name_ok(self):
''' After stripping entered name, check that it is a sensible
ConfigParser file section name. Return it if it is, '' if not.
'''
name = self.name.get().strip()
if not name: #no name specified
tkMessageBox.showerror(title='Name Error',
message='No name specified.', parent=self)
elif len(name)>30: #name too long
tkMessageBox.showerror(title='Name Error',
message='Name too long. It should be no more than '+
'30 characters.', parent=self)
name = ''
elif name in self.used_names:
tkMessageBox.showerror(title='Name Error',
message='This name is already in use.', parent=self)
name = ''
return name
def MenuOk(self):
"Simple validity check for a sensible menu item name"
menuOk = True
menu = self.menu.get()
menu.strip()
if not menu:
tkMessageBox.showerror(title='Menu Item Error',
message='No menu item specified',
parent=self)
self.entryMenu.focus_set()
menuOk = False
elif len(menu) > 30:
tkMessageBox.showerror(title='Menu Item Error',
message='Menu item too long:'
'\nLimit 30 characters.',
parent=self)
self.entryMenu.focus_set()
menuOk = False
return menuOk
def PathOk(self):
"Simple validity check for menu file path"
pathOk = True
path = self.path.get()
path.strip()
if not path: #no path specified
tkMessageBox.showerror(title='File Path Error',
message='No help file path specified.',
parent=self)
self.entryPath.focus_set()
pathOk = False
elif path.startswith(('www.', 'http')):
pass
else:
if path[:5] == 'file:':
path = path[5:]
if not os.path.exists(path):
tkMessageBox.showerror(title='File Path Error',
message='Help file path does not exist.',
parent=self)
self.entryPath.focus_set()
pathOk = False
return pathOk
def open(self, filename, action=None):
assert filename
filename = self.canonize(filename)
if os.path.isdir(filename):
# This can happen when bad filename is passed on command line:
tkMessageBox.showerror(
"File Error",
"%r is a directory." % (filename,),
master=self.root)
return None
key = os.path.normcase(filename)
if key in self.dict:
edit = self.dict[key]
edit.top.wakeup()
return edit
if action:
# Don't create window, perform 'action', e.g. open in same window
return action(filename)
else:
return self.EditorWindow(self, filename, key)
configSectionNameDialog.py 文件源码
项目:python2-tracer
作者: extremecoders-re
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def name_ok(self):
''' After stripping entered name, check that it is a sensible
ConfigParser file section name. Return it if it is, '' if not.
'''
name = self.name.get().strip()
if not name: #no name specified
tkMessageBox.showerror(title='Name Error',
message='No name specified.', parent=self)
elif len(name)>30: #name too long
tkMessageBox.showerror(title='Name Error',
message='Name too long. It should be no more than '+
'30 characters.', parent=self)
name = ''
elif name in self.used_names:
tkMessageBox.showerror(title='Name Error',
message='This name is already in use.', parent=self)
name = ''
return name
def MenuOk(self):
"Simple validity check for a sensible menu item name"
menuOk = True
menu = self.menu.get()
menu.strip()
if not menu:
tkMessageBox.showerror(title='Menu Item Error',
message='No menu item specified',
parent=self)
self.entryMenu.focus_set()
menuOk = False
elif len(menu) > 30:
tkMessageBox.showerror(title='Menu Item Error',
message='Menu item too long:'
'\nLimit 30 characters.',
parent=self)
self.entryMenu.focus_set()
menuOk = False
return menuOk
def PathOk(self):
"Simple validity check for menu file path"
pathOk = True
path = self.path.get()
path.strip()
if not path: #no path specified
tkMessageBox.showerror(title='File Path Error',
message='No help file path specified.',
parent=self)
self.entryPath.focus_set()
pathOk = False
elif path.startswith(('www.', 'http')):
pass
else:
if path[:5] == 'file:':
path = path[5:]
if not os.path.exists(path):
tkMessageBox.showerror(title='File Path Error',
message='Help file path does not exist.',
parent=self)
self.entryPath.focus_set()
pathOk = False
return pathOk
def open(self, filename, action=None):
assert filename
filename = self.canonize(filename)
if os.path.isdir(filename):
# This can happen when bad filename is passed on command line:
tkMessageBox.showerror(
"File Error",
"%r is a directory." % (filename,),
master=self.root)
return None
key = os.path.normcase(filename)
if key in self.dict:
edit = self.dict[key]
edit.top.wakeup()
return edit
if action:
# Don't create window, perform 'action', e.g. open in same window
return action(filename)
else:
return self.EditorWindow(self, filename, key)
def view_file(parent, title, filename, encoding=None, modal=True):
try:
if encoding:
import codecs
textFile = codecs.open(filename, 'r')
else:
textFile = open(filename, 'r')
except IOError:
tkMessageBox.showerror(title='File Load Error',
message='Unable to load file %r .' % filename,
parent=parent)
except UnicodeDecodeError as err:
showerror(title='Unicode Decode Error',
message=str(err),
parent=parent)
else:
return view_text(parent, title, textFile.read(), modal)
def play_plugin(self):
if self.plugin_dir_path.get() == "":
tkMessageBox.showerror("Error", "No plugin to play")
return
if self.ip_addr.get() == "":
tkMessageBox.showerror("Error", "No IP Address")
return
while (not self.test_auth()):
self.authenticate_with_aurora()
time.sleep(0.5)
iprint("Playing plugin")
self.sound_module.run_music_processor()
time.sleep(1)
iprint("Playing music processor")
self.sound_module.run_thread(self.ip_addr.get(), self.plugin_dir_path.get(), self.palette_path.get(), self.palette_entered)
def write_palette_for_sdk(self):
iprint("writing out palette to file")
self.palette_path.set(self.plugin_dir_path.get() + self.directory_divider + "palette")
if self.plugin_dir_path.get() == "":
tkMessageBox.showerror("Error", "Please enter the path to the plugin")
return;
try:
open_file = open(self.plugin_dir_path.get() + self.directory_divider + "palette", "w+")
except IOError, errinfo:
tkMessageBox.showerror("Error", "Could not write to directory." + str(errinfo))
return
palette_dict = self.palette
try:
palette_dict["palette"]
except TypeError:
palette_dict = {}
palette_dict["palette"] = self.palette
self.palette_entered = (len(self.palette) > 0)
open_file.write(json.dumps(palette_dict))
open_file.close()
def extract():
try:
print filename
except NameError:
tkMessageBox.showerror(title='File Selection', message='No PKG File Selected.')
try:
print outputFolder
except NameError:
global outputFolder
outputFolder = os.path.dirname(filename)
print outputFolder
if sys.platform.__contains__("linux"):
os.system("./pkg_dec '"+filename+"' '"+outputFolder+"/output'")
os.remove("out.bin")
tkMessageBox.showinfo(title='File Selection', message='Extraction Complete!')
if sys.platform.__contains__("win"):
os.system("pkg_dec.exe '"+filename+"' '"+outputFolder+"/output'")
os.remove("out.bin")
tkMessageBox.showinfo(title='File Selection', message='Extraction Complete!')
sys.stdout.flush()
openFolder(outputFolder + "/output")
def _UpdateFirmwareCmd(self):
q = tkMessageBox.showwarning('Update Fimware','Warning! Interrupting firmare update may lead to non functional PiJuice HAT.', parent=self.frame)
if q:
print 'Updating fimware'
inputFile = '/usr/share/pijuice/data/firmware/PiJuice.elf.binary'
curAdr = pijuice.config.interface.GetAddress()
if curAdr:
adr = format(curAdr, 'x')
ret = 256 - subprocess.call(['pijuiceboot', adr, inputFile])#subprocess.call([os.getcwd() + '/stmboot', adr, inputFile])
print 'firm res', ret
if ret == 256:
tkMessageBox.showinfo('Firmware update', 'Finished succesfully!', parent=self.frame)
else:
errorStatus = self.firmUpdateErrors[ret] if ret < 11 else ' UNKNOWN'
msg = ''
if errorStatus == 'I2C_BUS_ACCESS_ERROR':
msg = 'Check if I2C bus is enabled.'
elif errorStatus == 'INPUT_FILE_OPEN_ERROR':
msg = 'Firmware binary file might be missing or damaged.'
elif errorStatus == 'STARTING_BOOTLOADER_ERROR':
msg = 'Try to start bootloader manualy. Press and hold button SW3 while powering up RPI and PiJuice.'
tkMessageBox.showerror('Firmware update failed', 'Reason: ' + errorStatus + '. ' + msg, parent=self.frame)
else:
tkMessageBox.showerror('Firmware update', 'Unknown pijuice I2C address', parent=self.frame)
def _ApplyNewConfig(self, v):
for i in range(0, len(pijuice.config.leds)):
ledConfig = {'function':self.ledConfigsSel[i].get(), 'parameter':{'r':self.paramList[i*3].get(), 'g':self.paramList[i*3+1].get(), 'b':self.paramList[i*3+2].get()}}
if ( self.configs[i] == None
or ledConfig['function'] != self.configs[i]['function']
or ledConfig['parameter']['r'] != self.configs[i]['parameter']['r']
or ledConfig['parameter']['g'] != self.configs[i]['parameter']['g']
or ledConfig['parameter']['b'] != self.configs[i]['parameter']['b']
):
status = pijuice.config.SetLedConfiguration(pijuice.config.leds[i], ledConfig)
#event.widget.set('')
if status['error'] == 'NO_ERROR':
self.applyBtn.configure(state="disabled")
#time.sleep(0.2)
#config = pijuice.config.GetLedConfiguration(pijuice.config.leds[i])
#if config['error'] == 'NO_ERROR':
# event.widget.current(pijuice.config.ledFunctions.index(config['data']['function']))
#else:
# event.widget.set(config['error'])
else:
tkMessageBox.showerror('Apply LED Configuration', status['error'], parent=self.frame)
#event.widget.set(status['error'])
def _UpdateFirmwareCmd(self):
q = tkMessageBox.showwarning('Update Fimware','Warning! Interrupting firmare update may lead to non functional PiJuice HAT.', parent=self.frame)
if q:
print 'Updating fimware'
inputFile = '/usr/share/pijuice/data/firmware/PiJuice.elf.binary'
curAdr = pijuice.config.interface.GetAddress()
if curAdr:
adr = format(curAdr, 'x')
ret = 256 - subprocess.call(['pijuiceboot', adr, inputFile])#subprocess.call([os.getcwd() + '/stmboot', adr, inputFile])
print 'firm res', ret
if ret == 256:
tkMessageBox.showinfo('Firmware update', 'Finished succesfully!', parent=self.frame)
else:
errorStatus = self.firmUpdateErrors[ret] if ret < 11 else ' UNKNOWN'
msg = ''
if errorStatus == 'I2C_BUS_ACCESS_ERROR':
msg = 'Check if I2C bus is enabled.'
elif errorStatus == 'INPUT_FILE_OPEN_ERROR':
msg = 'Firmware binary file might be missing or damaged.'
elif errorStatus == 'STARTING_BOOTLOADER_ERROR':
msg = 'Try to start bootloader manualy. Press and hold button SW3 while powering up RPI and PiJuice.'
tkMessageBox.showerror('Firmware update failed', 'Reason: ' + errorStatus + '. ' + msg, parent=self.frame)
else:
tkMessageBox.showerror('Firmware update', 'Unknown pijuice I2C address', parent=self.frame)
def _UpdateFirmwareCmd(self):
q = tkMessageBox.showwarning('Update Fimware','Warning! Interrupting firmare update may lead to non functional PiJuice HAT.', parent=self.frame)
if q:
print 'Updating fimware'
inputFile = '/usr/share/pijuice/data/firmware/PiJuice.elf.binary'
curAdr = pijuice.config.interface.GetAddress()
if curAdr:
adr = format(curAdr, 'x')
ret = 256 - subprocess.call(['pijuiceboot', adr, inputFile])#subprocess.call([os.getcwd() + '/stmboot', adr, inputFile])
print 'firm res', ret
if ret == 256:
tkMessageBox.showinfo('Firmware update', 'Finished succesfully!', parent=self.frame)
else:
errorStatus = self.firmUpdateErrors[ret] if ret < 11 else ' UNKNOWN'
msg = ''
if errorStatus == 'I2C_BUS_ACCESS_ERROR':
msg = 'Check if I2C bus is enabled.'
elif errorStatus == 'INPUT_FILE_OPEN_ERROR':
msg = 'Firmware binary file might be missing or damaged.'
elif errorStatus == 'STARTING_BOOTLOADER_ERROR':
msg = 'Try to start bootloader manualy. Press and hold button SW3 while powering up RPI and PiJuice.'
tkMessageBox.showerror('Firmware update failed', 'Reason: ' + errorStatus + '. ' + msg, parent=self.frame)
else:
tkMessageBox.showerror('Firmware update', 'Unknown pijuice I2C address', parent=self.frame)
def _ApplyNewConfig(self, v):
for i in range(0, len(pijuice.config.leds)):
ledConfig = {'function':self.ledConfigsSel[i].get(), 'parameter':{'r':self.paramList[i*3].get(), 'g':self.paramList[i*3+1].get(), 'b':self.paramList[i*3+2].get()}}
if ( self.configs[i] == None
or ledConfig['function'] != self.configs[i]['function']
or ledConfig['parameter']['r'] != self.configs[i]['parameter']['r']
or ledConfig['parameter']['g'] != self.configs[i]['parameter']['g']
or ledConfig['parameter']['b'] != self.configs[i]['parameter']['b']
):
status = pijuice.config.SetLedConfiguration(pijuice.config.leds[i], ledConfig)
#event.widget.set('')
if status['error'] == 'NO_ERROR':
self.applyBtn.configure(state="disabled")
#time.sleep(0.2)
#config = pijuice.config.GetLedConfiguration(pijuice.config.leds[i])
#if config['error'] == 'NO_ERROR':
# event.widget.current(pijuice.config.ledFunctions.index(config['data']['function']))
#else:
# event.widget.set(config['error'])
else:
tkMessageBox.showerror('Apply LED Configuration', status['error'], parent=self.frame)
#event.widget.set(status['error'])
def _UpdateFirmwareCmd(self):
q = tkMessageBox.showwarning('Update Fimware','Warning! Interrupting firmare update may lead to non functional PiJuice HAT.', parent=self.frame)
if q:
print 'Updating fimware'
inputFile = '/usr/share/pijuice/data/firmware/PiJuice.elf.binary'
curAdr = pijuice.config.interface.GetAddress()
if curAdr:
adr = format(curAdr, 'x')
ret = 256 - subprocess.call(['pijuiceboot', adr, inputFile])#subprocess.call([os.getcwd() + '/stmboot', adr, inputFile])
print 'firm res', ret
if ret == 256:
tkMessageBox.showinfo('Firmware update', 'Finished succesfully!', parent=self.frame)
else:
errorStatus = self.firmUpdateErrors[ret] if ret < 11 else ' UNKNOWN'
msg = ''
if errorStatus == 'I2C_BUS_ACCESS_ERROR':
msg = 'Check if I2C bus is enabled.'
elif errorStatus == 'INPUT_FILE_OPEN_ERROR':
msg = 'Firmware binary file might be missing or damaged.'
elif errorStatus == 'STARTING_BOOTLOADER_ERROR':
msg = 'Try to start bootloader manualy. Press and hold button SW3 while powering up RPI and PiJuice.'
tkMessageBox.showerror('Firmware update failed', 'Reason: ' + errorStatus + '. ' + msg, parent=self.frame)
else:
tkMessageBox.showerror('Firmware update', 'Unknown pijuice I2C address', parent=self.frame)
def _ApplyNewConfig(self, v):
for i in range(0, len(pijuice.config.leds)):
ledConfig = {'function':self.ledConfigsSel[i].get(), 'parameter':{'r':self.paramList[i*3].get(), 'g':self.paramList[i*3+1].get(), 'b':self.paramList[i*3+2].get()}}
if ( self.configs[i] == None
or ledConfig['function'] != self.configs[i]['function']
or ledConfig['parameter']['r'] != self.configs[i]['parameter']['r']
or ledConfig['parameter']['g'] != self.configs[i]['parameter']['g']
or ledConfig['parameter']['b'] != self.configs[i]['parameter']['b']
):
status = pijuice.config.SetLedConfiguration(pijuice.config.leds[i], ledConfig)
#event.widget.set('')
if status['error'] == 'NO_ERROR':
self.applyBtn.configure(state="disabled")
#time.sleep(0.2)
#config = pijuice.config.GetLedConfiguration(pijuice.config.leds[i])
#if config['error'] == 'NO_ERROR':
# event.widget.current(pijuice.config.ledFunctions.index(config['data']['function']))
#else:
# event.widget.set(config['error'])
else:
tkMessageBox.showerror('Apply LED Configuration', status['error'], parent=self.frame)
#event.widget.set(status['error'])
def _UpdateFirmwareCmd(self):
q = tkMessageBox.showwarning('Update Fimware','Warning! Interrupting firmare update may lead to non functional PiJuice HAT.', parent=self.frame)
if q:
print 'Updating fimware'
inputFile = '/usr/share/pijuice/data/firmware/PiJuice.elf.binary'
curAdr = pijuice.config.interface.GetAddress()
if curAdr:
adr = format(curAdr, 'x')
ret = 256 - subprocess.call(['pijuiceboot', adr, inputFile])#subprocess.call([os.getcwd() + '/stmboot', adr, inputFile])
print 'firm res', ret
if ret == 256:
tkMessageBox.showinfo('Firmware update', 'Finished succesfully!', parent=self.frame)
else:
errorStatus = self.firmUpdateErrors[ret] if ret < 11 else ' UNKNOWN'
msg = ''
if errorStatus == 'I2C_BUS_ACCESS_ERROR':
msg = 'Check if I2C bus is enabled.'
elif errorStatus == 'INPUT_FILE_OPEN_ERROR':
msg = 'Firmware binary file might be missing or damaged.'
elif errorStatus == 'STARTING_BOOTLOADER_ERROR':
msg = 'Try to start bootloader manualy. Press and hold button SW3 while powering up RPI and PiJuice.'
tkMessageBox.showerror('Firmware update failed', 'Reason: ' + errorStatus + '. ' + msg, parent=self.frame)
else:
tkMessageBox.showerror('Firmware update', 'Unknown pijuice I2C address', parent=self.frame)
def show_popup_message(self, popup_type="warning", title_to_show="ALLERT", message_to_show="THIS IS AN ALLERT MESSAGE", parent_window=None, refresh=True):
"""
Displays error or warning messages and refreshes the sequence window.
"""
# show_error_message
# show_warning_message
if parent_window == None:
parent_window = self.main_window
if popup_type == "error":
tkMessageBox.showerror(title_to_show, message_to_show, parent=parent_window)
elif popup_type == "info":
tkMessageBox.showinfo(title_to_show, message_to_show, parent=parent_window)
elif popup_type == "warning":
tkMessageBox.showwarning(title_to_show, message_to_show, parent=parent_window)
if refresh:
self.gridder()
def startup_pymod(app):
"""
Checks if NumPy and Biopython (PyMod core Python dependencies) are present before launching
PyMod.
"""
if not numpy_found:
title = "Import Error"
message = "NumPy is not installed on your system. Please install it in order to use PyMod."
tkMessageBox.showerror(title, message)
return False
if not biopython_found:
title = "Import Error"
message = "Biopython is not installed on your system. Please install it in order to use PyMod."
tkMessageBox.showerror(title, message)
return False
import pymod_main
pymod_main.pymod_launcher(app, pymod_plugin_name, __version__, __revision__)
def OpenSave():
global f
# Attempt to Extract the
try:
z = ZipFile(ent_SaveFile.get())
DebugPrint(" + Successfully opened save file archive")
x = z.extract('savedata', os.getcwd(), 'w#qjH_xaZ~Fm')
DebugPrint(" + Successfully extracted save contents")
f = open(x, 'r+b')
DebugPrint(" + Successfully opened save file data")
return 1
except:
f = None
DebugPrint(" + Unable to open save file data")
tkMessageBox.showerror("FireGUI Error", "Unable to open savedata.dat file")
return 0
# Function to close the save file
def ValidateConfig():
global val_Stable
err_message = ""
if ent_SaveFile.get() == "":
err_message = "\nSaveData.dat location is empty"
if ent_OutputFile.get() == "":
err_message = err_message + "\nOutput file location is empty"
if val_Stable.get() == 1:
if lst_Stables.index(ACTIVE) == 0:
err_message = err_message + "\nStable not selected"
if err_message != "":
tkMessageBox.showerror("FireGUI Error", "Unable to process: \n%s" % err_message)
return 0
else:
return 1
# Function to update all the missions to rank S
def run_to(self):
try:
advance_amount = int(self.years_box.get())
if advance_amount > 0:
self.advancing = True
self.end_year = self.year + advance_amount
self.after_id = self.parent.after(self.delay.get(), self.main_loop)
else:
self.end_year = self.year
tkMessageBox.showerror('Negative Years', 'Cannot advance a negative or zero amount of time.')
except ValueError:
self.end_year = self.year
tkMessageBox.showerror('Invalid Year', '"{}" is not a valid integer'.format(self.years_box.get()))
return
def setup(root, wm=''):
"""1) find the files and/or settings (::wm_default::setup).
Takes one optional argument: wm, the name of the window manager
as a string, if known. One of: windows gnome kde1 kde2 cde kde.
"""
try:
try:
# Make sure Tcl/Tk knows wm_default is installed
root.tk.eval("package require wm_default")
except:
# Try again with this directory on the Tcl/Tk path
dir = os.path.dirname (self.__file__)
root.tk.eval('global auto_path; lappend auto_path {%s}' % dir)
root.tk.eval("package require wm_default")
except:
t, v, tb = sys.exc_info()
text = "Error loading WmDefault\n"
for line in traceback.format_exception(t,v,tb): text = text + line + '\n'
try:
tkMessageBox.showerror ('WmDefault Error', text)
except:
sys.stderr.write( text )
return root.tk.call('::wm_default::setup', wm)
def handlePlotData(self):
print "Getting headers!"
if self.data is not None:
d = ChooseAxesDialog(self.root, self.data.get_headers())
else:
tkMessageBox.showerror("No Open File", "Please open a file first!")
print "First Open a Data File!!"
return
if d.result is not None:
self.x_label_name.set(d.result[0][0])
self.y_label_name.set(d.result[0][1])
self.z_label_name.set(d.result[0][2])
self.reset()
spatial_headers = [h for h in d.result[0] if h != "None"]
other_headers = d.result[1:]
self.buildPoints(spatial_headers, other_headers, self.data)
def handleLinearRegression(self):
if self.data is None:
tkMessageBox.showerror("No Open File", "Please open a file first!")
return
d = LinearRegressionDialog(self.root, self.data.get_headers())
if d.result is not None:
if d.result[0] == "None" or d.result[1] == "None":
tkMessageBox.showwarning(title="Incorrect Parameters", message="Option cannot be 'None'")
else:
self.objects = []
self.linreg_endpoints = None
self.linreg_line_objects = []
self.reset()
self.updateAxes()
self.regression_mode = True
self.buildLinearRegression(headers=d.result)
# build and display the regression on the plot