def CheckForWx(forceVersion=os.getenv('GRASS_WXVERSION', None)): """Try to import wx module and check its version :param forceVersion: force wxPython version, eg. '2.8' """ if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: import wxversion except ImportError as e: raise ImportError(e) if forceVersion: wxversion.select(forceVersion) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.__version__ if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) except ImportError as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e) sys.exit(1) except (ValueError, wxversion.VersionError) as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \ '%s.' % (str(e)) sys.exit(1) except locale.Error as e: print >> sys.stderr, "Unable to set locale:", e os.environ['LC_ALL'] = ''
def CheckForWx(): """Try to import wx module and check its version""" if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: import wxversion except ImportError as e: raise ImportError(e) # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1])) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.__version__ if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) except ImportError as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e) sys.exit(1) except (ValueError, wxversion.VersionError) as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \ '%s.' % (str(e)) sys.exit(1) except locale.Error as e: print >> sys.stderr, "Unable to set locale:", e os.environ['LC_ALL'] = ''
def run(): """ Run application. """ # parse options options = _parse_opt() # logowanie from wxgtd.lib.logging_setup import logging_setup logging_setup('wxgtd.log', options.debug, options.debug_sql) # app config from wxgtd.lib import appconfig config = appconfig.AppConfig('wxgtd.cfg', 'wxgtd') config.load_defaults(config.get_data_file('defaults.cfg')) config.load() config.debug = options.debug # importowanie wx try: import wxversion try: wxversion.ensureMinimal("2.8") except wxversion.AlreadyImportedError: _LOG.warn('Wx Already Imported') except wxversion.VersionError: _LOG.error("WX version > 2.8 not found; avalable: %s", wxversion.checkInstalled()) except ImportError, err: _LOG.error('No wxversion.... (%s)' % str(err))
def CheckForWx(): """Try to import wx module and check its version""" if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: import wxversion except ImportError as e: raise ImportError(e) # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1])) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.version().split(' ')[0] if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) except ImportError as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e) sys.exit(1) except (ValueError, wxversion.VersionError) as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \ '%s.' % (str(e)) sys.exit(1) except locale.Error as e: print >> sys.stderr, "Unable to set locale:", e os.environ['LC_ALL'] = ''
def init_stage2(use_gui): """\ Initialise the remaining (non-path) parts of wxGlade (second stage) @param use_gui: Starting wxGlade GUI @type use_gui: Boolean """ common.use_gui = use_gui if use_gui: # ensure minimal wx version if not hasattr(sys, 'frozen') and \ 'wxversion' not in sys.modules and \ 'wx' not in sys.modules: import wxversion wxversion.ensureMinimal("2.6") # store current platform (None is default) import wx common.platform = wx.Platform # codewrites, widgets and sizers are loaded in class main.wxGladeFrame else: # use_gui has to be set before importing config import config config.init_preferences() common.load_code_writers() common.load_widgets() common.load_sizers()
def check(self): try: import wxversion except ImportError: raise CheckFailed("requires wxPython") try: _wx_ensure_failed = wxversion.AlreadyImportedError except AttributeError: _wx_ensure_failed = wxversion.VersionError try: wxversion.ensureMinimal("2.8") except _wx_ensure_failed: pass try: import wx backend_version = wx.VERSION_STRING except ImportError: raise CheckFailed("requires wxPython") # Extra version check in case wxversion lacks AlreadyImportedError; # then VersionError might have been raised and ignored when # there really *is* a problem with the version. major, minor = [int(n) for n in backend_version.split(".")[:2]] if major < 2 or (major < 3 and minor < 8): raise CheckFailed("Requires wxPython 2.8, found %s" % backend_version) BackendAgg.force = True return "version %s" % backend_version
def ensure(recommended, minimal): """Ensures the minimal version of wxPython is installed. - minimal: as string (eg. '2.6')""" #wxversion try: import wxversion if wxversion.checkInstalled(recommended): wxversion.select(recommended) else: wxversion.ensureMinimal(minimal) import wx return wx except ImportError: sys.stdout.write(_t('Warning: python-wxversion is not installed.\n')) #wxversion failed, import wx anyway params = {'recommended': recommended, 'minimal': minimal} try: import wx except ImportError: message = _t('Error: wxPython %(recommended)s' \ ' (or at least %(minimal)s) can not' \ ' be found, but is required.' ) % params +\ '\n\n' + _t('Please (re)install it.') sys.stderr.write(message) if sys.platform.startswith('linux') and \ os.path.exists('/usr/bin/zenity'): call('''zenity --error --text="%s"\n\n''' % message + \ _t("This application needs 'python-wxversion' " \ "and 'python-wxgtk%(recommended)s' " \ "(or at least 'python-wxgtk%(minimal)s')." ) % params, shell=True) sys.exit() #wxversion failed but wx is available, check version again params['version'] = wx.VERSION_STRING if wx.VERSION_STRING < minimal: class MyApp(wx.App): def OnInit(self): result = wx.MessageBox( _t("This application is known to be compatible" \ " with\nwxPython version(s) %(recommended)s" \ " (or at least %(minimal)s),\nbut you have " \ "%(version)s installed." ) % params + "\n\n" +\ _t("Please upgrade your wxPython."), _t("wxPython Version Error"), style=wx.ICON_ERROR) return False app = MyApp() app.MainLoop() sys.exit() #wxversion failed, but wx is the right version anyway return wx
def CheckForWx(): """!Try to import wx module and check its version""" if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 1, 1] try: try: import wxversion except ImportError, e: raise ImportError(e) # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1])) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.version().split(' ')[0] if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.')))
def init_stage2(use_gui): """Initialise the remaining (non-path) parts of wxGlade (second stage) use_gui: Starting wxGlade GUI""" config.use_gui = use_gui if use_gui: # import proper wx-module using wxversion, which is only available in Classic if compat.IS_CLASSIC: if not hasattr(sys, "frozen") and 'wx' not in sys.modules: try: import wxversion wxversion.ensureMinimal('2.8') except ImportError: msg = _( 'Please install missing Python module "wxversion".') logging.error(msg) sys.exit(msg) try: import wx except ImportError: msg = _('Please install missing Python module "wxPython".') logging.error(msg) sys.exit(msg) # store current version and platform ('not_set' is default) config.platform = wx.Platform config.wx_version = wx.__version__ if sys.platform == "win32": # register ".wxg" extension try: import msw msw.register_extensions(["wxg"], "wxGlade") if not os.path.exists(config.rc_file): config.inform_screen_reader = msw.check_for_screen_reader() except ImportError: pass # codewrites, widgets and sizers are loaded in class main.wxGladeFrame else: # use_gui has to be set before importing config common.init_preferences() common.init_codegen()
def CheckForWx(forceVersion=os.getenv('GRASS_WXVERSION', None)): """Try to import wx module and check its version :param forceVersion: force wxPython version, eg. '2.8' """ if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: # Note that Phoenix doesn't have wxversion anymore import wxversion except ImportError as e: # if there is no wx raises ImportError import wx return if forceVersion: wxversion.select(forceVersion) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx # noqa: F811 version = parse_version_string(wx.__version__) if version < minVersion: raise ValueError("Your wxPython version is {}".format( wx.__version__)) except ImportError as e: print('ERROR: wxGUI requires wxPython. %s' % str(e), file=sys.stderr) print( 'You can still use GRASS GIS modules in' ' the command line or in Python.', file=sys.stderr) sys.exit(1) except (ValueError, wxversion.VersionError) as e: message = "ERROR: wxGUI requires wxPython >= {version}: {error}".format( version=version_as_string(minVersion), error=e) print(message, file=sys.stderr) sys.exit(1) except locale.Error as e: print("Unable to set locale:", e, file=sys.stderr) os.environ['LC_ALL'] = ''
def _check_environment(): # Check Python version py2_7_or_better = hasattr(sys, 'version_info') and sys.version_info >= (2,7) py3 = hasattr(sys, 'version_info') and sys.version_info >= (3,0) if not py2_7_or_better: exit('This application requires Python 2.7 or later.') if py3: exit('This application cannot run under Python 3.x. Try Python 2.7 instead.') # Check for dependencies if not _running_as_bundle(): try: import wxversion except ImportError: exit( 'This application requires wxPython to be installed. ' + 'Download it from http://wxpython.org/') else: # Check version and display dialog to user if an upgrade is needed. # If a dialog is displayed, the application will exit automatically. wxversion.ensureMinimal('2.8') try: import wx except ImportError: is_64bits = sys.maxsize > 2**32 if is_64bits: python_bitness = '64-bit' else: python_bitness = '32-bit' exit( 'wxPython found but couldn\'t be loaded. ' + 'Your Python is %s. Are you sure the installed wxPython is %s?' % (python_bitness, python_bitness)) try: import BeautifulSoup except ImportError: exit( 'This application requires BeautifulSoup to be installed. ' + 'Download it from http://www.crummy.com/software/BeautifulSoup/')
def CheckForWx(forceVersion=os.getenv('GRASS_WXVERSION', None)): """Try to import wx module and check its version :param forceVersion: force wxPython version, eg. '2.8' """ if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: # Note that Phoenix doesn't have wxversion anymore import wxversion except ImportError as e: # if there is no wx raises ImportError import wx return if forceVersion: wxversion.select(forceVersion) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.__version__ if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) except ImportError as e: print('ERROR: wxGUI requires wxPython. %s' % str(e), file=sys.stderr) print( 'You can still use GRASS GIS modules in' ' the command line or in Python.', file=sys.stderr) sys.exit(1) except (ValueError, wxversion.VersionError) as e: print('ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + '%s.' % (str(e)), file=sys.stderr) sys.exit(1) except locale.Error as e: print("Unable to set locale:", e, file=sys.stderr) os.environ['LC_ALL'] = ''
def init_stage2(use_gui): """\ Initialise the remaining (non-path) parts of wxGlade (second stage) @param use_gui: Starting wxGlade GUI @type use_gui: bool """ config.use_gui = use_gui if use_gui: # import proper wx-module using wxversion, which is only available in Classic if compat.IS_CLASSIC: if not hasattr(sys, "frozen") and 'wx' not in sys.modules: try: import wxversion wxversion.ensureMinimal('2.8') except ImportError: msg = _( 'Please install missing Python module "wxversion".') logging.error(msg) sys.exit(msg) try: import wx except ImportError: msg = _('Please install missing Python module "wxPython".') logging.error(msg) sys.exit(msg) # store current version and platform ('not_set' is default) config.platform = wx.Platform config.wx_version = wx.__version__ # codewrites, widgets and sizers are loaded in class main.wxGladeFrame else: # use_gui has to be set before importing config common.init_preferences() if config.preferences.log_debug_info: log.setDebugLevel() common.init_codegen()
def CheckForWx(): """!Try to import wx module and check its version""" if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 1, 1] unsupportedVersion = [2, 9, 0, 0] try: try: import wxversion except ImportError, e: raise ImportError(e) # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1])) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.version().split(' ')[0] if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) if map(int, version.split('.')) >= unsupportedVersion: print >> sys.stderr, 'ERROR: wxGUI does not support wxPython %s yet.' % version sys.exit(1)
import strings ## Quick tests - which is there? ## Using imp will find a module very quickly, faster than import x import imp ## PIL : Is it there? try: from PIL import Image, ImageFont, ImageDraw except: print strings.PILError raise SystemExit try: import wxversion ## Dec 2007: noticed that it may not be installed along with wxPython.... wxversion.ensureMinimal("3.0") ## June 25, 2016 - wxversion is now 3.0 ## I am remarking out the old line: ##wxversion.ensureMinimal("2.8") except: print strings.wxVersionError print try: imp.find_module("wx") except: print strings.wxError raise SystemExit ## 2017 - Using GLib to detect the XDG_DATA_HOME stuff. ## Not fatal if it's missing - will fall-back to old fonty paths. try:
except ImportError: if system == "debian-based": notfound.append("python-numpy") notfound.append("python-numpy-ext") else: notfound.append("NumPy or SciPy") if not hasattr(sys, "frozen"): wx_version = (2, 8, 0, 0) wx_version_str = '.'.join([str(x) for x in wx_version[0:2]]) try: import wxversion if os.path.exists("wxversion"): wxversion.select(open("wxversion").read()) else: wxversion.ensureMinimal(wx_version_str) except ImportError, e: pass try: import wx if not cmp(wx_version, wx.__version__.split('.')): raise ImportError("wxPython was too old") print "wxPython version is", wx.__version__ except (ImportError, KeyError), e: print e if system == "debian-based": notfound.append("python-wxgtk2.8") else:
# (c) 2013-2014 Andreas Pflug # # Licensed under the Apache License, # see LICENSE.TXT for conditions of usage import sys if not hasattr(sys, 'frozen'): import wxversion import os, platform wxversion._EM_DEBUG=True if platform.system() == "Darwin": wxversion.select('2.9.4') else: wxversion.ensureMinimal("3.0") if platform.system() == "Windows": minVersion="3.0.1.1" for iv in wxversion._find_installed(): ver=os.path.basename(iv.pathname).split('-')[1] if ver >= minVersion: break if ver >= '3.0': for f in os.listdir(iv.pathname): if f.endswith('.egg-info'): ver=f.split('-')[1] if ver >= minVersion: break else: raise wxversion.VersionError('wxPython minimum usable version is %s' % minVersion)
def run_tests(): "Create test suites and run all tests" # evaluate command line options first parser = OptionParser( usage="%prog [options] Test wxGlade components", ) parser.set_defaults(kind='cli') parser.add_option( '-g', '--gui', action='store_const', dest='kind', const='gui', help=_('Test GUI components instead of non-GUI components'), ) parser.add_option( '-c', '--compile', action='store_const', dest='kind', const='compile', help=_('Compile generated C++ source code'), ) options = parser.parse_args()[0] suites = [] # disable logging first because the initialisation logs path details and # other details logging.disable(logging.WARNING) wxglade.init_stage1() wxglade.init_localization() wxglade.init_stage2(options.kind == 'gui') # select proper wxversion if options.kind == 'gui' and compat.IS_CLASSIC: # import proper wx-module using wxversion if not hasattr(sys, "frozen") and 'wx' not in sys.modules: try: import wxversion wxversion.ensureMinimal('2.8') except ImportError: print(_('Please install missing Python module "wxversion".')) sys.exit(1) except wxversion.VersionError: print(_('The requested wxPython version is not found. Disable GUI tests.')) sys.exit() if options.kind == 'gui': modules = ['test_gui.py'] import wx i = wx.Locale(wx.LANGUAGE_DEFAULT) elif options.kind == 'compile': modules = ['test_compile.py'] else: # options.kind == 'cli' modules = ['test_external.py', 'test_codegen.py', 'test_bugs.py', ] # try to import all files as modules for module_name in modules: module_name = os.path.splitext(module_name)[0] fp, path, info = imp.find_module(module_name, ['./tests']) try: module = imp.load_module(module_name, fp, path, info) finally: # Make sure fp is closed properly if fp: fp.close() # search all test cases in the loaded module suites.append(unittest.findTestCases(module)) # summarise all suites and run tests all_tests = unittest.TestSuite(suites) unittest.TextTestRunner(verbosity=2).run(all_tests)
>python lh-abc.py need Python, WxPython in order to run from source code. """ import __builtin__ import sys import os import time import gettext import getopt import tempfile import mmap if not getattr(sys, 'frozen', None): import wxversion wxversion.ensureMinimal('2.9.0.1') import wx from traceback import format_exc from threading import Thread from BitTornado.__init__ import product_name, version_short from BitTornado.bencode import bencode, bdecode from LMG.Utility.utility import Utility from LMG.Utility.constants import * from LMG.GUI.menus import MenuBar from LMG.GUI.lists import TransferList from LMG.GUI.taskbaricon import TaskBarIcon
# Used to guarantee to use at least Wx2.8 import wxversion wxversion.ensureMinimal('2.8') import wx import wx.aui import matplotlib as mpl from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar class Plot(wx.Panel): def __init__(self, parent, id=-1, dpi=None, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.figure = mpl.figure.Figure(dpi=dpi, figsize=(2, 2)) self.canvas = Canvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer) class PlotNotebook(wx.Panel): def __init__(self, parent, id=-1): wx.Panel.__init__(self, parent, id=id) self.nb = wx.aui.AuiNotebook(self)
from __future__ import absolute_import, division, print_function from builtins import str from builtins import object import sys import psychopy if not hasattr(sys, 'frozen'): try: import wxversion haveWxVersion = True except ImportError: haveWxVersion = False # if wxversion doesn't exist hope for the best if haveWxVersion: wxversion.ensureMinimal('2.8') # because this version has agw import wx try: from agw import advancedsplash as AS except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.advancedsplash as AS """ Aug 2017: for now we want to turn off warning for AddSimpleTool The warning says we should use this in wx4.0: item = tb.AddTool( wx.ID_ANY, bitmap=newBmp, labe=key.replace('Ctrl+', ctrlKey), shortHelp=_translate("Create new python file")) BUT in 3.0.2 that raises an error so it's too early to switch. """ import warnings
Task Coach is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Task Coach is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import wxversion, sys wxversion.ensureMinimal("2.8") sys.path.append('../tools') import os, img2py def extractIcon(iconZipFile, pngFilename, pngZipped): pngFile = file(pngFilename, 'wb') pngFile.write(iconZipFile.read(pngZipped)) pngFile.close() def addIcon(pngName, pngFilename, iconPyFile, first): options = [ '-F', '-i', '-c', '-a', '-n%s' % pngName, pngFilename, iconPyFile
#!/usr/bin/env python2 # Part of the PsychoPy library # Copyright (C) 2014 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). import sys, psychopy import copy if not hasattr(sys, 'frozen'): import wxversion wxversion.ensureMinimal('2.8') # because this version has agw import wx try: from agw import advancedsplash as AS except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.advancedsplash as AS #NB keep imports to a minimum here because splash screen has not yet shown #e.g. coder and builder are imported during app.__init__ because they take a while from psychopy import preferences, logging#needed by splash screen for the path to resources/psychopySplash.png from psychopy.app import connections import sys, os, threading # knowing if the user has admin priv is generally a good idea for security. # not actually needed; psychopy should never need anything except normal user # see older versions for code to detect admin (e.g., v 1.80.00) class MenuFrame(wx.Frame): """A simple, empty frame with a menubar that should be the last frame to close on a mac """ def __init__(self, parent=None, ID=-1, app=None, title="PsychoPy2"):
def visualizer(data): """ Stand Alone app to analize solution data are a dictionary with :sol: solution """ # Used to guarantee to use at least Wx2.8 import wxversion wxversion.ensureMinimal('2.8') import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as Toolbar from matplotlib.figure import Figure import wx import wx.xrc as xrc class PlotPanel(wx.Panel): """ Inspired by example "embedding_in_wx3.py" Bare matplotlib panel """ def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((3,2)) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) ## Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) ## This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.ALL | wx.EXPAND) ## Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.ALL) self.sizer = sizer self.SetSizer(sizer) self.Fit() def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass class InstrumentFrame(wx.Frame): def __init__(self, title = "Visualizer GUI", parent = None,): ## A Frame is a top-level window wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = (700,600)) self.Show(True) # Show the frame. self.stdF = wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.buttonF = wx.Font(16, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD) self.SetFont( self.stdF ) self.buttons = [] ## Set Sizer and Automatic Layout ##- 4 boxes 1) 3d/contour ## 2) slice/animation ## 3) Open/save ## 4) parameters.. self.box = wx.FlexGridSizer(2,2) self.box.SetFlexibleDirection(wx.BOTH) ### Info ###### ### ==== ###### self.info = wx.StaticText(self, label = "blah blah") #self.description.SetSize((300,-1)) self.box.Add(self.info, 0, wx.ALL , border = 4) ### 3d/contour ###### ### ========== ###### self.contour_plot = PlotPanel(self) bSizer = wx.BoxSizer( wx.VERTICAL ) ## Slider to select the frame self.m_slider = wx.Slider( self, wx.ID_ANY, 0, 0, 100, # Size wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL ) def onslider(evt): self.line.set_ydata( abs(self.data['sol'][self.m_slider.GetValue()])**2 ) self.vline.set_xdata( [self.z[self.m_slider.GetValue()], self.z[self.m_slider.GetValue()]]) self.contour_plot.canvas.draw() self.slice_plot.canvas.draw() self.Bind(wx.EVT_SCROLL, onslider, self.m_slider) bSizer.Add(self.contour_plot, 1,wx.ALL | wx.EXPAND, border = 2) bSizer.Add( self.m_slider, 0, wx.ALL|wx.EXPAND, border= 2 ) self.box.Add(bSizer, 1,wx.ALL | wx.EXPAND, border = 2) ### Button Box ###### ### ========== ###### buttonbox = wx.BoxSizer(wx.VERTICAL) ## Load btn = wx.Button(self, label= "Load") btn.SetFont( self.buttonF ) ## Bind the event def callbackWrap(evt): dlg = wx.FileDialog(None, style = wx.OPEN, wildcard = "*.mat") if dlg.ShowModal() == wx.ID_OK: # User has selected something, get the path, set the window's title to the path filename = dlg.GetPath() try: data = loadmat(filename, appendmat = False) self.setData(data) except: print(filename," - File error") ##v = callback() ##txt.SetLabel(str(v)) ## Bind the event self.Bind(wx.EVT_BUTTON, callbackWrap, btn) buttonbox.Add(btn, 0, wx.ALL | wx.EXPAND, border = 4) ## Save btn = wx.Button(self, label= "Save") btn.SetFont( self.buttonF ) def callbackWrap(evt): dlg = wx.FileDialog(None, style = wx.SAVE, wildcard = ".mat") if dlg.ShowModal() == wx.ID_OK: # User has selected something, get the path, set the window's title to the path filename = dlg.GetPath() try: savemat(filename, self.data, appendmat = False) except: print(filename," - File error") ## Bind the event self.Bind(wx.EVT_BUTTON, callbackWrap, btn) buttonbox.Add(btn, 0, wx.ALL | wx.EXPAND, border = 4) self.box.Add(buttonbox) ### Slice ###### ### ========== ###### self.slice_plot = PlotPanel(self) self.box.Add( self.slice_plot, 1, wx.EXPAND |wx.ALL, 2 ) ## Flexible Grid #### ## ------------- #### self.box.AddGrowableRow(0,1) self.box.AddGrowableRow(1,1) self.box.AddGrowableCol(0,1) self.box.AddGrowableCol(1,3) self.SetSizer(self.box) self.Layout() def setData(self, data): """ Update with new data """ self.data = data ## Data ### solutions = data["sol"] self.z = data.get("z", linspace(0,1, len(solutions)) ).flatten() t = data.get("t", linspace(0,1, len(solutions[0]))).flatten() w = data.get("w", linspace(-1,1, len(solutions[0]))).flatten() pot = data.get("pump", None) title = data.get("title", ["Beam propagation"])[0] notes = data.get("notes", [""])[0] date = data.get("date",[""])[0] info = "%s\n%s\n%s"%(title,date, notes) ## Notes ## self.info.SetLabel(info) ## Plot ### axis = self.contour_plot.fig.add_subplot(111) axis.hold(False) axis.contourf(self.z,t,abs(array(solutions).T)**2, 20, aspect = 'auto')#, cmap = matplotlib.cm.autumn) self.vline = axis.axvline(self.z[-1], linewidth=3, color='k') axis = self.slice_plot.fig.add_subplot(111) axis.hold(False) axis.plot(t,abs(array(solutions[0]))**2, label = "Start", color="grey") axis.hold(True) self.line, = axis.plot(t,abs(array(solutions[-1]))**2, label = "Final") if pot==None: axis.plot(t,abs(pot)**2, label = "Potential", color="red") axis.legend() ## Slider ### self.m_slider.SetRange(0,len(solutions)-1) self.m_slider.SetValue(len(solutions)-1) self.contour_plot.canvas.draw() self.slice_plot.canvas.draw() app = wx.App(False) f = InstrumentFrame() f.setData(data) app.MainLoop()
__version__ = Release.version from nbshell.utils import delta_time import sys import os import re from optparse import OptionParser import unittest delta_time('standard modules loaded') #dbg #wxversion messes up with the sys.path. so I have to fix it oldpath = sys.path[0] try: import wxversion wxversion.ensureMinimal('2.5.3') except: pass #I will try to run it, but it might not work sys.path[0:0] = [oldpath] import wx delta_time('wx loaded') #dbg from nbshell.utils import * from nbshell import ipnNotebookWidget,ipnDocument,frame,tester from ipnNotebookWidget import * # in case you wonder ipn comes from Interactive Python Notebook from ipnDocument import * from frame import ipnFrame delta_time('nbshell modules loaded') #dbg from IPython import ultraTB # For developer use: let's park a nice formatted traceback printer in
from wx import BeginBusyCursor, CallAfter, EndBusyCursor, GetActiveWindow, \ GetApp, Platform, SafeYield, WakeUpIdle, Yield, YieldIfNeeded if False: required = (2, 8, 0, 0) # minimum wxPython version required_str = ".".join(map(str, required)) # if a multiversion wxPython is installed, attempt to get a required version try: # for wxversion, we only take the first two numbers import wxversion wxversion_req = ".".join(map(str, required[:2])) try: wxversion.ensureMinimal(wxversion_req) except wxversion.VersionError, e: # it should also be possible to import wax after wxPython is imported. # this VersionError prevents this, so we work around it. if e.args[0].find("must be called before wxPython is imported") < 0: raise except ImportError: # will fail if it's not a multiversion installation pass import wx assert wx.VERSION >= required, \ "This version of Wax requires wxPython %s or later" % (required_str,) DEBUG = 0 # set to 1 to enable debugging messages
--- cycle.py.orig +++ cycle.py @@ -9,6 +9,9 @@ import os, sys, gettext import locale +prefix = os.path.split(os.path.dirname(sys.argv[0]))[0] +sys.path.append(os.path.join(prefix, 'lib', 'cycle')) + import wxversion wxversion.ensureMinimal('2.5.3') import wx
# See LICENSE.txt for details. "Launch the plover application." # Python 2/3 compatibility. from __future__ import print_function import os import sys import traceback import argparse WXVER = '3.0' if not hasattr(sys, 'frozen'): import wxversion wxversion.ensureMinimal(WXVER) if sys.platform.startswith('darwin'): import appnope import wx import plover.gui.main import plover.oslayer.processlock from plover.oslayer.config import CONFIG_DIR, ASSETS_DIR from plover.config import CONFIG_FILE, Config from plover import log from plover import __name__ as __software_name__ from plover import __version__ def show_error(title, message):
# Workaround for a bug in Ubuntu 10.10 os.environ['XLIB_SKIP_ARGB_VISUALS'] = '1' # This prevents a message printed to the console when wx.lib.masked # is imported from taskcoachlib.widgets on Ubuntu 12.04 64 bits... try: from mx import DateTime except ImportError: pass if not hasattr(sys, "frozen"): # These checks are only necessary in a non-frozen environment, i.e. we # skip these checks when run from a py2exe-fied application import wxversion wxversion.ensureMinimal("2.8-unicode", optionsRequired=True) try: import taskcoachlib # pylint: disable=W0611 except ImportError: # On Ubuntu 12.04, taskcoachlib is installed in /usr/share/pyshared, # but that folder is not on the python path. Don't understand why. # We'll add it manually so the application can find it. sys.path.insert(0, '/usr/share/pyshared') try: import taskcoachlib # pylint: disable=W0611 except ImportError: sys.stderr.write( '''ERROR: cannot import the library 'taskcoachlib'. Please see https://answers.launchpad.net/taskcoach/+faq/1063 for more information and possible resolutions. ''')
import multiprocessing import optparse as op import os import sys import shutil if sys.platform == 'win32': import _winreg else: if sys.platform != 'darwin': import wxversion #wxversion.ensureMinimal('2.8-unicode', optionsRequired=True) #wxversion.select('2.8-unicode', optionsRequired=True) wxversion.ensureMinimal('3.0') import wx #from wx.lib.pubsub import setupv1 #new wx from wx.lib.pubsub import setuparg1# as psv1 #from wx.lib.pubsub import Publisher #import wx.lib.pubsub as ps from wx.lib.pubsub import pub as Publisher #import wx.lib.agw.advancedsplash as agw #if sys.platform == 'linux2': # _SplashScreen = agw.AdvancedSplash #else: # if sys.platform != 'darwin': # _SplashScreen = wx.SplashScreen
# # Copyright (c) 2010 Martin Natano <*****@*****.**> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import wxversion; wxversion.ensureMinimal('2.8') from . import MyImage
#------------------------------------------------------------------------- import multiprocessing import optparse as op import os import sys import shutil if sys.platform == 'win32': import _winreg else: if sys.platform != 'darwin': import wxversion #wxversion.ensureMinimal('2.8-unicode', optionsRequired=True) #wxversion.select('2.8-unicode', optionsRequired=True) wxversion.ensureMinimal('3.0') import wx #from wx.lib.pubsub import setupv1 #new wx from wx.lib.pubsub import setuparg1 # as psv1 #from wx.lib.pubsub import Publisher #import wx.lib.pubsub as ps from wx.lib.pubsub import pub as Publisher #import wx.lib.agw.advancedsplash as agw #if sys.platform == 'linux2': # _SplashScreen = agw.AdvancedSplash #else: # if sys.platform != 'darwin': # _SplashScreen = wx.SplashScreen
#!/usr/bin/env python import sys if sys.platform.startswith('win') and sys.executable.lower().endswith('pythonw.exe'): from cStringIO import StringIO sys.stdout = StringIO() MIN_WX_VERSION = '2.5.4.1' GET_WXPYTHON = 'Get it from http://www.wxpython.org!' try: import wxversion if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): pass #probably not the first call to this module: wxPython already loaded else: wxversion.ensureMinimal(MIN_WX_VERSION) except ImportError: #the old fashioned way as not everyone seems to have wxversion installed try: import wx if wx.VERSION_STRING < MIN_WX_VERSION: print 'You need to upgrade wxPython to v%s (or higher) to run SPE.'%MIN_WX_VERSION print GET_WXPYTHON sys.exit() except ImportError: print "Error: SPE requires wxPython, which doesn't seem to be installed." print GET_WXPYTHON sys.exit() print 'Warning: the package python-wxversion was not found, please install it!' print 'SPE will continue anyway, but not all features (such as wxGlade) might work.'
Task Coach is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import sys if not hasattr(sys, "frozen"): # These checks are only necessary in a non-frozen environment, i.e. we # skip these checks when run from a py2exe-fied application import wxversion try: wxversion.ensureMinimal("2.8-unicode", optionsRequired=True) except: pass try: import taskcoachlib except ImportError: sys.stderr.write('''ERROR: cannot import the library 'taskcoachlib'. Please see http://www.taskcoach.org/faq.html for more information and possible resolutions.''') sys.exit(1) def start(): from taskcoachlib import config, application options, args = config.ApplicationOptionParser().parse_args() app = application.Application(options, args)
## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. # [08-05-2011] vipera: UN IDE PARA DESARROLLAR EN PYTHON import os import random import sys # Comprobamos versión de wxPython. try: WX_VERSION = '2.8' import wxversion wxversion.ensureMinimal(WX_VERSION) except ImportError: print 'Se necesita wxPython v%s para lanzar vipera'% WX_VERSION sys.exit() import wx import wx.lib.ogl as ogl import wx.lib.agw.pybusyinfo as PBI from frontend_vipera import fp from configuracion_vipera import conf_vipera, proy_por_defecto, enter from i18n_vipera import t, ENGLISH, SPANISH licencia = u''' vipera, an application designer for Python Copyright (C) 2011 Angel Luis Garcia Garcia
# See LICENSE.txt for details. "Launch the plover application." # Python 2/3 compatibility. from __future__ import print_function import os import sys import traceback import argparse WXVER = '3.0' if not hasattr(sys, 'frozen'): import wxversion wxversion.ensureMinimal(WXVER) if sys.platform.startswith('darwin'): import appnope import wx import plover.gui.main import plover.oslayer.processlock from plover.oslayer.config import CONFIG_DIR, ASSETS_DIR from plover.config import CONFIG_FILE, Config from plover import log from plover import __name__ as __software_name__ from plover import __version__ def show_error(title, message): """Report error to the user.
#!/usr/bin/python # -*- coding: iso-8859-15 -*- import sys try: import wxversion; wxversion.ensureMinimal("2.8") import wx.aui except ImportError: print "Can't laod wx.aui module, please check that you have installed wxpython > 2.8 and taht it is your default install" sys.exit(1) #used for about dialog from wx.lib.wordwrap import wordwrap #used for ipython GUI objects from IPython.gui.wx.ipython_view import IPShellWidget from IPython.gui.wx.ipython_history import IPythonHistoryPanel #used to invoke ipython1 wx implementation ### FIXME ### temporary disabled due to interference with 'show_in_pager' hook is_sync_frontend_ok = False try: from IPython.frontend.wx.ipythonx import IPythonXController except ImportError: is_sync_frontend_ok = False #used to create options.conf file in user directory from IPython.ipapi import get __version__ = 0.10 __version_str__ = "0.10"
# -*- coding: utf-8 -*- # # Copyright 2014 by Paweł T. Jochym <*****@*****.**> # This code is licensed under GPL v2 or later. # The oryginal repo is at: https://github.com/jochym/pointsel # from __future__ import division, print_function from numpy import array import numpy as np from scipy.optimize import bisect import sys, os, math import matplotlib import wxversion wxversion.ensureMinimal("2.8") matplotlib.use("WXAgg") from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavToolbar from matplotlib.backends.backend_wx import _load_bitmap, bind, StatusBarWx from matplotlib.figure import Figure from matplotlib.widgets import RectangleSelector from matplotlib.patches import Rectangle from matplotlib import rcParams import wx import matplotlib as mpl import matplotlib.pyplot as plt
DEBUG = 0 # set to 1 to enable debugging messages from wx import BeginBusyCursor, CallAfter, EndBusyCursor, GetActiveWindow, \ GetApp, Platform, SafeYield, WakeUpIdle, Yield, YieldIfNeeded if False: required = (2, 8, 0, 0) # minimum wxPython version required_str = ".".join(map(str, required)) # if a multiversion wxPython is installed, attempt to get a required version try: # for wxversion, we only take the first two numbers import wxversion wxversion_req = ".".join(map(str, required[:2])) try: wxversion.ensureMinimal(wxversion_req) except wxversion.VersionError, e: # it should also be possible to import wax after wxPython is imported. # this VersionError prevents this, so we work around it. if e.args[0].find( "must be called before wxPython is imported") < 0: raise except ImportError: # will fail if it's not a multiversion installation pass import wx assert wx.VERSION >= required, \ "This version of Wax requires wxPython %s or later" % (required_str,) DEBUG = 0 # set to 1 to enable debugging messages
import wxversion wxversion.ensureMinimal('2.8') import wx import wx.aui import matplotlib as mpl from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas # from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar from matplotlib.backends.backend_wx import NavigationToolbar2Wx as Toolbar import collections class PlotCollection: def __init__(self, window_name="", window_size=(800, 600)): """ This class places matplot figures in tabs on a wx window (make sure to use unique figure ids between different PlotCollection instances or wxwidget may segfault) e.g. usage: from sm import PlotCollection import pylab as pl #create the plot as usual fig1=pl.figure() pl.plot([1,2],[2,3]) fig2=pl.figure() pl.plot([3,1],[4,5]) #add to collection plotter = PlotCollection.PlotCollection("My window name") plotter.add_figure("My plot1 name", fig1)
#!/usr/bin/env python2 # Part of the PsychoPy library # Copyright (C) 2014 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). import sys, psychopy import copy if not hasattr(sys, "frozen"): import wxversion wxversion.ensureMinimal("2.8") # because this version has agw import wx try: from agw import advancedsplash as AS except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.advancedsplash as AS # NB keep imports to a minimum here because splash screen has not yet shown # e.g. coder and builder are imported during app.__init__ because they take a while from psychopy import preferences, logging # needed by splash screen for the path to resources/psychopySplash.png from psychopy.app import connections import sys, os, threading # knowing if the user has admin priv is generally a good idea for security. # not actually needed; psychopy should never need anything except normal user # see older versions for code to detect admin (e.g., v 1.80.00) class MenuFrame(wx.Frame):