コード例 #1
1
def UserInterface(Settingz):

    import wx
    from body import randorator, check_icon, check_windows
# Загружается основной модуль программы и графическая библиотека.
# Program icon existence checking module is loaded.
# Windows platform checking module is loaded.
    from i18n.locator import locale

# WxPython version dependent hacks.
    from wxversion import getInstalled
    try:
        if int(getInstalled()[0][0]) < 3:
            WxPython3 = False
        else:
            WxPython3 = True
    except:
# Strange Windows portable issue.
        WxPython3 = True

    windows = check_windows()
# Here it is a value to check if the program is run under windows.

#===========================|Text_Control_Class|============================#

    class MyTextCtrl:
        def __init__(self, place_frame, place_sizer, string_class, DefaultValue, choise_class = False, button_add = False, DefaultSelection = False):
# Принимается frame прикрепления виджета, sizer упаковки и текст надписи.
# A string value to add a combobox or a button could be also inputed.

            def button_finfo(event):
                wx.MessageBox(button_add, locale(u"ui_iftxt", Settingz["str_langu"]), wx.OK | wx.ICON_INFORMATION)
# Here it is a function to show information window.

            if choise_class or button_add:
                x_box = 45
            else:
                x_box = 0
            x_text = 150 - x_box
# The text widget width will be modified if a combobox or a button is enabled.

            self.sizer_class = wx.BoxSizer(wx.HORIZONTAL)
            place_sizer.Add(self.sizer_class)
# Создаётся упаковщик с горизонтальным порядком заполнения и добавляется в переданный упаковщик.
            self.text_class = wx.StaticText(place_frame, label = string_class, size = (x_text, -1))
            if choise_class:
                self.box_class = wx.Choice(place_frame, size = (x_box, -1), choices = choise_class)
            elif button_add:
                self.button_class = wx.Button(place_frame, label = u"?", size = (x_box, -1))
# The combobox widget or the button will be created if it is set.

            self.control_class = wx.TextCtrl(place_frame, size = (90, -1))
            self.control_class.SetValue(DefaultValue)
# Описание значения и поле ввода.
            self.sizer_class.Add(self.text_class, flag = wx.ALIGN_CENTER_VERTICAL)
            if choise_class:
                self.sizer_class.Add(self.box_class)
                self.box_class.SetSelection(DefaultSelection)
            elif button_add:
                self.sizer_class.Add(self.button_class)
                place_frame.Bind(wx.EVT_BUTTON, button_finfo, self.button_class)
# The combobox widget or the button will be shown if it is set.

            self.sizer_class.Add(self.control_class)
# Описание (с выравниванием по вертикали) и поле упаковываются в соответствующий упаковщик.
        def GetValue(self):
            return(self.control_class.GetValue())
# Метод передаётся от чекбокса объекту описываемого класса.
        def GetCurrentSelection(self):
            if self.box_class.GetCurrentSelection() == 1:
                return(True)
            else:
                return(False)
# Here it is a method to get user decision from a combobox as a logical value.

#=============================|Check_Box_Class|=============================#

    class MyCheckBox:
        def __init__(self, place_frame, place_sizer, string_class, logical_class):
# Принимается frame прикрепления, sizer упаковки, текст надписи и маркер отметки.
            self.check_class = wx.CheckBox(place_frame, label = string_class)
            place_sizer.Add(self.check_class)
# Создаётся и добавляется в переданный упаковщик чекбокс.
            if logical_class:
                self.check_class.SetValue(logical_class)
# Если задано, чекбокс отмечается.
        def IsChecked(self):
            return(self.check_class.IsChecked())
# Метод передаётся от чекбокса объекту описываемого класса.

#==============================|Button_Class|===============================#

    class MyButton:
        def __init__(self, place_frame, place_sizer, string_class, command_class):
# Принимается frame прикрепления виджета, sizer упаковки, строковое значение для надписи и функция.
            self.button_class = wx.Button(place_frame, label = string_class, size = (240, -1))
            place_sizer.Add(self.button_class)
            place_frame.Bind(wx.EVT_BUTTON, command_class, self.button_class)
# Создаётся и добавляется в переданный упаковщик кнопка. Присваевается функция для выполнения.

#========================|Generate_Button_Function|=========================#

    def button_fmake(event):
# Функция для кнопки генерации. Записывается с аргументом события.
        dict_val = {
        "str_langu": Settingz["str_langu"],
        "str_minim": sizer_mini.GetValue(),
        "str_maxim": sizer_maxi.GetValue(),
        "str_quant": sizer_n.GetValue(),
        "str_avera": sizer_mean.GetValue(),
        "str_rsd_p": sizer_rsd.GetValue(),
        "str_round": sizer_round.GetValue(),
        "log_punct": check_punctu.IsChecked(),
        "log_verbo": check_verbosity.IsChecked(),
        "log_algor": check_algorithm.IsChecked(),
        "log_min_v": sizer_mini.GetCurrentSelection(),
        "log_max_v": sizer_maxi.GetCurrentSelection(),
        "log_rsd_a": check_rsd_a.IsChecked(),
        "log_rsd_w": sizer_rsd.GetCurrentSelection(),
        "log_horiz": check_horizontal_output.IsChecked(),
        "str_sortm": sizer_sortm.GetValue()}
# Here it is a dictionary with almost all output values.
        dict_out = randorator(dict_val)
# The output dictionary is transfered to the external function to get text back.
        text_out.SetValue(dict_out["str_infoz"] + dict_out["str_numbz"])
# Запись текста в поле.
        if check_copy.IsChecked():
            if wx.TheClipboard.Open():
                wx.TheClipboard.SetData(wx.TextDataObject(dict_out["str_numbz"]))
                wx.TheClipboard.Close()
# Если задано, открывается, заполняется и закрывается буфер обмена.

#=============================|Program_Window|==============================#

    app_root = wx.App(0)
# Инициация тулкита. Zero to disable output window creating under windows.

    FrameStyle = wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX
    frame_root = wx.Frame(parent = None, style = FrameStyle)
# Создаётся окно: его можно сворачивать, есть системное меню и кнопка закрытия.
    if Settingz["log_ontop"]:
        frame_root.SetWindowStyleFlag(FrameStyle | wx.STAY_ON_TOP)
# Window always on top behavior if configured.
    frame_root.SetTitle(locale(u"ui_title", Settingz["str_langu"]))
# Задаётся заголовок окна.
    window_icon = check_icon("ico")
    if window_icon != "":
        frame_root.SetIcon(wx.Icon(window_icon, type = wx.BITMAP_TYPE_ICO))
# Window icon is loaded.

    panel_root = wx.Panel(frame_root, style = wx.TAB_TRAVERSAL)
# На корневой фрейм добавляется корневая панель,
# чтобы можно было переключаться между элементами по нажатию кнопки Tab.
# Применяется соответствующий стиль, хотя работает и без него.
    if not WxPython3:
        panel_root.SetBackgroundColour(wx.NullColor)
# Окно заливается цветом по умолчанию для корректной отрисовки под windows.

    sizer_root = wx.BoxSizer(wx.VERTICAL)
    panel_root.SetSizer(sizer_root, deleteOld=True)
# Создаётся упаковщик с вертикальным порядком заполнения и применяется к окну.

#==================================|Title|==================================#

    text_title = wx.StaticText(panel_root, style = wx.ALIGN_CENTER | wx.EXPAND)
# Текстовый виджет c выравниванием по центру, растянут по ширине.
    text_title.SetLabel(locale(u"ui_about", Settingz["str_langu"]))
# Задаётся текст виджета.

    sizer_root.Add(text_title, flag = wx.ALIGN_CENTER)
# Текстовый виджет добавляется в корневой упаковщик.

#=============================|Text_Data_Input|=============================#

    sizer_mini = MyTextCtrl(panel_root, sizer_root, locale(u"ui_minim", Settingz["str_langu"]), Settingz["str_minim"], ["", "+"], False, Settingz["log_min_v"])

    sizer_maxi = MyTextCtrl(panel_root, sizer_root, locale(u"ui_maxim", Settingz["str_langu"]), Settingz["str_maxim"], ["", "+"], False, Settingz["log_max_v"])

    sizer_n = MyTextCtrl(panel_root, sizer_root, locale(u"ui_quant", Settingz["str_langu"]), Settingz["str_quant"])

    sizer_mean = MyTextCtrl(panel_root, sizer_root, locale(u"ui_avera", Settingz["str_langu"]),  Settingz["str_avera"])

    sizer_rsd = MyTextCtrl(panel_root, sizer_root, locale(u"ui_rsd_p", Settingz["str_langu"]), Settingz["str_rsd_p"], ["<", "~"], False, Settingz["log_rsd_w"])

    sizer_round = MyTextCtrl(panel_root, sizer_root, locale(u"ui_round", Settingz["str_langu"]), Settingz["str_round"], False, locale(u"ui_ifrnd", Settingz["str_langu"]))

    sizer_sortm = MyTextCtrl(panel_root, sizer_root, locale(u"ui_sortm", Settingz["str_langu"]), Settingz["str_sortm"], False, locale(u"ui_ifsrt", Settingz["str_langu"]))
# Рисуются упаковщики с описаниями значений и полями ввода.

#=================================|Buttons|=================================#

    sizer_buttonz = wx.BoxSizer(wx.HORIZONTAL)
    sizer_root.Add(sizer_buttonz)
# Создаётся упаковщик для кнопок и добавляется в корневой упаковщик.

    button_make = MyButton(panel_root, sizer_buttonz, locale(u"ui_gen_b", Settingz["str_langu"]), button_fmake)
# Кнопка запуска генерирования.

#===============================|Check_Boxes|===============================#

    check_copy = MyCheckBox(panel_root, sizer_root, locale(u"ui_clipb", Settingz["str_langu"]), Settingz["log_clipb"])
# Чекбокс для включения/выключения автоматического копирования значений.
# Активен — копировать.

    check_punctu = MyCheckBox(panel_root, sizer_root, locale(u"ui_punct", Settingz["str_langu"]), Settingz["log_punct"])
# Чекбокс для переключения между точками и запятыми. Неактивен – запятые.
    check_verbosity = MyCheckBox(panel_root, sizer_root, locale(u"ui_error", Settingz["str_langu"]), Settingz["log_verbo"])
# Чекбокс для включения/выключения вывода сообщений об ошибках.
# Активен – выводить.
    if ((not WxPython3) and windows):
        check_algorithm = MyCheckBox(panel_root, sizer_root, locale(u"ui_true1", Settingz["str_langu"]), Settingz["log_algor"])
    else:
        check_algorithm = MyCheckBox(panel_root, sizer_root, locale(u"ui_truer", Settingz["str_langu"]), Settingz["log_algor"])
# Here it is a checkbox to enable true random numbers generation.
# randomdotorg is licenced under GPLv3 and/or any later. The creator is
# Clovis Fabricio. See more at http://code.google.com/p/randomdotorg/
# wx.CheckBox under windows doesn't suppoth the newline symbol:
# see more at http://trac.wxwidgets.org/ticket/9495
    check_rsd_a = MyCheckBox(panel_root, sizer_root, locale(u"ui_rsd_a", Settingz["str_langu"]), Settingz["log_rsd_a"])
# Here it is a checkbox to configure true RSD value output.
# It isn't activated by default and RSD isn't outputed.
    check_horizontal_output = MyCheckBox(panel_root, sizer_root, locale(u"ui_horiz", Settingz["str_langu"]), Settingz["log_horiz"])
# Horizontal (default&True) / vertical numbers output checkbox.

#============================|Text_Data_Output|=============================#

    text_out = wx.TextCtrl(panel_root, style = wx.EXPAND | wx.TE_MULTILINE, size = (-1, 150))
# Текстовый виджет c выравниванием по центру, растянут по ширине.
    sizer_root.Add(text_out, flag = wx.EXPAND)
# Текстовый виджет добавляется в корневой упаковщик.

#=============================|Program_Window|==============================#

    window_size = panel_root.GetBestSize()
    if ((not WxPython3) and windows):
        window_size[0] += ((235 - 230) + 1)
        window_size[1] += ((400 - 377) + 1)
# Size should be enlaged to fix wx/windows bug.
    frame_root.SetSize(window_size)
# Окно подбирает оптимальный размер, для размещения всех виджетов.
    frame_root.Show()
# Показать окно.
    app_root.MainLoop()
コード例 #2
0
ファイル: Utilities.py プロジェクト: pheplex/DESMining
def GetWXVersionFromIni():
	""" Return the wx version loaded in devsimpy (from ini file if exist)
	"""

	### update the init file into GetUserConfigDir
	parser = ConfigParser.SafeConfigParser()
	path = os.path.join(GetUserConfigDir(), 'devsimpy.ini')
	parser.read(path)

	section, option = ('wxversion', 'to_load')

	### if ini file exist we remove old section and option
	if os.path.exists(path):
		return parser.get(section, option)
	else:
		import wxversion
		### wxPython version
		wxv= map(lambda a: a.split('-')[0], wxversion.getInstalled())

		if wxv != []:
			a = wxv[0]
			### wx.__version__ is more precise than the values of wxv
			for v in wxv:
				if v in wx.__version__:
					a = v
			return a
		else:
			return wx.VERSION_STRING
コード例 #3
0
 def __init__(self, mpstate):
     super(HelpModule, self).__init__(mpstate, "help", "Help and version information", public = True)
     self.enabled = False
     self.add_command('mavhelp', self.cmd_help, "help and version information", "<about|site>")
     self.have_list = False
     
     #versioning info
     self.version = pkg_resources.require("mavproxy")[0].version
     self.host = platform.system() + platform.release()
     self.pythonversion = str(platform.python_version())
     if mp_util.has_wxpython:
         self.wxVersion = str(wxversion.getInstalled())
     else:
         self.wxVersion = ''
         
     #check for updates, if able
     if platform.system() == 'Windows':
         req = Request('http://firmware.diydrones.com/Tools/MAVProxy/')
         html = ''
         self.newversion = '1.0'
         try:
             filehandle = urlopen(req)
             html = filehandle.read()
         except HTTPError as e:
             self.newversion = 'Error: ', e.code
         except URLError as e:
             self.newversion =  'Error: ', e.reason
         else:
             #parse the webpage for the latest version
             begtags = [m.start() for m in re.finditer('>MAVProxySetup-', html)]
             for begtag in begtags:
                 endtag = html.find('.exe', begtag)
                 versiontag = html[begtag+15:endtag]
                 if not re.search('[a-zA-Z]', versiontag):
                     if self.mycmp(self.newversion, versiontag) < 0:
                         self.newversion = versiontag
     elif platform.system() == 'Linux':
         import xmlrpclib, pip
         pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
         available = pypi.package_releases('MAVProxy')
         if not available:
             self.newversion = 'Error finding update'
         else:        
             self.newversion = available[0]
             
     #and format the update string
     if re.search('[a-zA-Z]', self.newversion):
         self.newversion = "Error finding update: " + self.newversion
     elif self.newversion == self.version:
         self.newversion = "Running latest version"
     else:
         self.newversion = "New version " + self.newversion + " available (currently running " + self.version + ")"
         
     if mp_util.has_wxpython:
         self.menu_added_console = False
         self.menu = MPMenuSubMenu('Help',
                               items=[MPMenuItem('MAVProxy website', 'MAVProxy website', '', handler=MPMenuOpenWeblink('http://tridge.github.io/MAVProxy/')),
                                      MPMenuItem('Check for Updates', 'Check for Updates', '', handler=MPMenuChildMessageDialog(title="Updates", message=self.newversion)), 
                                      MPMenuItem('About', 'About', '', handler=MPMenuChildMessageDialog(title="About MAVProxy", message="MAVProxy Version " + self.version + "\nOS: " + self.host + "\nPython " +  self.pythonversion + "\nWXPython " + self.wxVersion))])
コード例 #4
0
ファイル: diagnostics.py プロジェクト: kfilipan/noysim
def checkWxPython(version):
  """ check if the specified version of wxPython is installed """
  # try to import the module
  try:
    import wxversion
  except:
    return 'Error: module wxPython not installed (correctly)'
  # check if the specified version is available
  v = wxversion.getInstalled()
  if version in v:
    return 'OK: module wxPython version %s installed' % version
  else:
    return 'Error: module wxPython version should be at least %s (installed: %s)' % (version, ', '.join(v))
コード例 #5
0
ファイル: diagnostics.py プロジェクト: bertdecoensel/noysim
def checkWxPython(version):
  """ check if the specified version of wxPython is installed """
  # try to import the module
  try:
    import wxversion
  except:
    return 'Error: module wxPython not installed (correctly)'
  # check if the specified version is available
  v = wxversion.getInstalled()
  if version in v:
    return 'OK: module wxPython version %s installed' % version
  else:
    return 'Error: module wxPython version should be at least %s (installed: %s)' % (version, ', '.join(v))
コード例 #6
0
def resolve_wxversion():
    patt = "%d\.%d[0-9\-\.A-Za-z]*-unicode"
    patts = "-unicode"

    versions = wxversion.getInstalled()
    if verbose:
        print 'wxPython Installed :', versions

    # need to select the more recent one with 'unicode'
    vSelected = None
    vSelectedMsg = ''
    for eachVersion in versions:
        for min in range(WXVERSION_MINOR1, WXVERSION_MINOR2 + 1):
            m = re.search(patt % (WXVERSION_MAJOR, min), eachVersion)
            if m:
                if min == WXVERSION_MINOR2:
                    vSelectedMsg = ''
                else:
                    vSelectedMsg = ' (deprecated version - think to update)'
                vSelected = eachVersion
                break
        if m:
            break

    if vSelected:
        print 'wxPython Selected  :', vSelected, vSelectedMsg
        wxversion.select(vSelected)
        return

    # no compatible version :-( : try to select any release
    bUnicode = False
    for eachVersion in versions:
        m = re.search(patts, eachVersion)
        if m:
            print 'wxPython Selected  :', eachVersion
            wxversion.select(eachVersion)
            bUnicode = True
            break

    if not bUnicode:
        # only ansi release :-( => use US lang
        setLang('us')

    import sys, wx, webbrowser
    app = wx.PySimpleApp()
    wx.MessageBox(
        message('wxversion_msg') % (WXVERSION_MAJOR, WXVERSION_MINOR2),
        message('wxversion_title'))
    app.MainLoop()
    webbrowser.open("http://wxpython.org/")
    sys.exit()
コード例 #7
0
def resolve_wxversion():
    patt = "%d\.%d[0-9\-\.A-Za-z]*-unicode"
    patts = "-unicode"

    versions = wxversion.getInstalled()
    if verbose:
        print 'wxPython Installed :',versions

    # need to select the more recent one with 'unicode'
    vSelected = None
    vSelectedMsg = ''
    for eachVersion in versions:
        for min in range(WXVERSION_MINOR1,WXVERSION_MINOR2+1):
            m = re.search( patt % (WXVERSION_MAJOR,min), eachVersion)
            if m:
                if min == WXVERSION_MINOR2:
                    vSelectedMsg = ''
                else:
                    vSelectedMsg = ' (deprecated version - think to update)'
                vSelected = eachVersion
                break
        if m:
            break

    if vSelected:
        print 'wxPython Selected  :',vSelected,vSelectedMsg
        wxversion.select(vSelected)
        return

    # no compatible version :-( : try to select any release
    bUnicode = False
    for eachVersion in versions:
        m = re.search(patts, eachVersion)
        if m:
            print 'wxPython Selected  :',eachVersion
            wxversion.select(eachVersion)
            bUnicode = True
            break

    if not bUnicode:
        # only ansi release :-( => use US lang
        setLang('us')

    import sys, wx, webbrowser
    app = wx.PySimpleApp()
    wx.MessageBox(message('wxversion_msg') % (WXVERSION_MAJOR,WXVERSION_MINOR2), message('wxversion_title'))
    app.MainLoop()
    webbrowser.open("http://wxpython.org/")
    sys.exit()
コード例 #8
0
ファイル: polymer.py プロジェクト: dwd/Polymer
def run():
    """
    A wrapper around main(), which handles profiling if requested.
    """
    import polymer.options
    opts = polymer.options.handle_options()[0]
    if opts.wxversion is not None:
        import wxversion
        if opts.wxversion == 'help':
            for x in wxversion.getInstalled():
                print "Installed:", x
            import sys
            sys.exit()
        else:
            wxversion.select( opts.wxversion )
    if opts.profile:
        import profile
        profile.run( 'main()', opts.profile )
        import pstats
        prof = pstats.Stats( opts.profile )
        prof.sort_stats( 'cumulative', 'calls' ).print_stats( 50 )
    else:
        main()
    return opts.debug
コード例 #9
0
def main(wx_version, cli_options):
    if platform.system() == 'Linux':
        try:
            # to fix some KDE display issues:
            del os.environ['GTK_RC_FILES']
            del os.environ['GTK2_RC_FILES']
        except (ValueError, KeyError):
            pass

    if not hasattr(sys, "frozen"):
        try:
            wxversion.select(wx_version)
        except wxversion.VersionError:
            print("\nFailed to load wxPython version %s!\n" % wx_version)
            sys.exit()

    import wx
    if 'unicode' not in wx.PlatformInfo:
        print(
            "\nInstalled version: %s\nYou need a unicode build of wxPython to run Metamorphose 2.\n"
            % wxversion.getInstalled())

    # wxversion changes path
    sys.path[0] = syspath

    import MainWindow

    class BoaApp(wx.App):
        def OnInit(self):
            self.main = MainWindow.create(None, cli_options)
            self.main.Show()
            self.SetTopWindow(self.main)
            return True

    application = BoaApp(0)
    application.MainLoop()
コード例 #10
0
ファイル: tribler.py プロジェクト: Antiade/tribler
logger = logging.getLogger(__name__)

# This import needs to be before any twisted or dispersy import so it can initalize the reactor in a separate thread
# No need to do reactor.run(), it gets started when imported
from Tribler.Core.Utilities.twisted_thread import reactor, stop_reactor

from Tribler.Main.Utility.utility import initialize_x11_threads
initialize_x11_threads()

# set wxpython version
import wxversion
try:
    # in the windows and mac distribution, there may be no version available.
    # so select a version only when there is any available.
    if wxversion.getInstalled():
        wxversion.select("2.8-unicode")
except wxversion.VersionError:
    logger.exception("Unable to use wxversion installed wxversions: %s", repr(wxversion.getInstalled()))


def run():
    from Tribler.Main.tribler_main import run as run_main
    run_main()

if sys.version_info[:2] != (2, 7):
    print >> sys.stderr, "Tribler needs python 2.7.X to run, current version: %s" % sys.version
    exit(1)

# Windows py2exe freezing tribler.py wreaks havoc with paths, imports, etc. So a
# tribler_exe.py module has been created which only role is to find this module
コード例 #11
0
ファイル: check_python.py プロジェクト: Moflexter/MoflexTer
import os, wxversion
print("wxversion(s): " + ", ".join(wxversion.getInstalled()))

if os.environ["POL_OS"] != "Mac":
    wxversion.ensureMinimal('2.8')

import wx
os._exit(0)
コード例 #12
0
	def __init__(self, parent):
		"""
			Constructor.
		"""
		wx.Panel.__init__(self, parent)

		### FileBrowse
		self.plugin_dir = filebrowse.DirBrowseButton(self, wx.ID_ANY, labelText=_("Plug-ins directory:"), toolTip=_("Change the plug-ins directory"), dialogTitle=_("Plugins directory..."))
		self.domain_dir = filebrowse.DirBrowseButton(self, wx.ID_ANY, labelText=_("Library directory:"), toolTip=_("Change the library directory"), dialogTitle=_("Libraries directory..."))
		self.out_dir = filebrowse.DirBrowseButton(self, wx.ID_ANY, labelText=_("Output directory:"), toolTip=_("Change the output directory"), dialogTitle=_("Output directory..."))

		self.plugin_dir.SetValue(PLUGINS_PATH)
		self.domain_dir.SetValue(DOMAIN_PATH)
		self.out_dir.SetValue(OUT_DIR)

		### StaticText
		self.st1 = wx.StaticText(self, wx.ID_ANY, _("Number of recent file:"))
		self.st2 = wx.StaticText(self, wx.ID_ANY, _("Font size:"))
		self.st3 = wx.StaticText(self, wx.ID_ANY, _("Deep of history item:"))
		self.st4 = wx.StaticText(self, wx.ID_ANY, _("wxPython version:"))

		self.st1.SetToolTipString(_("Feel free to change the length of list defining the recent opened files."))
		self.st2.SetToolTipString(_("Feel free to change the font size of DEVSimpy."))
		self.st3.SetToolTipString(_("Feel free to change the number of item for undo/redo command"))
		self.st4.SetToolTipString(_("Feel free to change the version of wxpython used loaded by DEVSimPy"))

		### number of opened file
		self.nb_opened_file = wx.SpinCtrl(self, wx.ID_ANY, '')
		self.nb_opened_file.SetRange(2, 20)
		self.nb_opened_file.SetValue(NB_OPENED_FILE)

		### Block font size
		self.font_size = wx.SpinCtrl(self, wx.ID_ANY, '')
		self.font_size.SetRange(2, 20)
		self.font_size.SetValue(FONT_SIZE)

		### number of undo/redo items
		self.nb_history_undo = wx.SpinCtrl(self, wx.ID_ANY, '')
		self.nb_history_undo.SetRange(2, 100)
		self.nb_history_undo.SetValue(NB_HISTORY_UNDO)

		### CheckBox
		self.cb1 = wx.CheckBox(self, wx.ID_ANY, _('Transparency'))
		self.cb1.SetToolTipString(_("Transparency for the detached frame of diagrams"))
		self.cb1.SetValue(__builtin__.__dict__['TRANSPARENCY'])

		### wxPython version
		wxv= map(lambda a: a.split('-')[0], wxversion.getInstalled())

		self.cb2 = wx.ComboBox(self, wx.ID_ANY, GetWXVersionFromIni(), choices= wxv, style=wx.CB_READONLY)
		self.cb2.SetToolTipString(_("Default version of wxPython."))
		self.default_wxv = self.cb2.GetValue()

		### Sizer
		box1 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, _('Properties')), orient=wx.VERTICAL)
		vsizer = wx.BoxSizer(wx.VERTICAL)
		hsizer = wx.GridSizer(4, 2, 20, 20)

		hsizer.AddMany( [	(self.st1, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
							(self.nb_opened_file, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
							(self.st3, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
							(self.nb_history_undo, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
							(self.st2, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
							(self.font_size, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
					(self.st4, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5),
					(self.cb2, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5)])

		vsizer.Add(self.plugin_dir, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
		vsizer.Add(self.domain_dir, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
		vsizer.Add(self.out_dir, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
		vsizer.Add(hsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
		vsizer.Add(self.cb1, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
		box1.Add(vsizer, 1, wx.EXPAND)

		### Set sizer
		self.SetSizer(box1)
		self.SetAutoLayout(True)
コード例 #13
0
ファイル: metamorphose2.py プロジェクト: RavenB/metamorphose2
sys.path[0] = path

class BoaApp(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        self.main = MainWindow.create(None)
        self.main.Show()
        self.SetTopWindow(self.main)
        return True


def main():
    if platform.system() == 'Linux':
        try:
            # to fix some KDE display issues:
            del os.environ['GTK_RC_FILES']
            del os.environ['GTK2_RC_FILES']
        except (ValueError, KeyError):
            pass

    application = BoaApp(0)
    application.MainLoop()


if __name__ == '__main__':
    if 'unicode' not in wx.PlatformInfo:
        print("\nInstalled version: %s\nYou need a unicode build of wxPython to run Metamorphose 2.\n"
              % wxversion.getInstalled())
    else:
        main()
コード例 #14
0
    print "scipy not installed!"
else:
    print "scipy:      ", scipy.version.version


try:
    import win32api
except ImportError:
    print "PyWin32 not installed!"
else:
    pw32_info = win32api.GetFileVersionInfo(win32api.__file__, '\\')
    print "PyWin32:    ", pw32_info['FileVersionLS'] >> 16


try:
    import matplotlib
except ImportError:
    print "matplotlib not installed!"
else:
    print "matplotlib: ", matplotlib.__version__


try:
    import wxversion
except ImportError:
    print "wxPython not installed!"
else:
    print "wxPython:   ",
    for elem in wxversion.getInstalled():
        print elem
コード例 #15
0
ファイル: plot_tests.py プロジェクト: mdkmdk/datavision
from numpy import linspace, sin
from pandas import DataFrame
import wxversion

wxversion.select(wxversion.getInstalled())
# wxversion.select('3.0-gtk2')
from traits.api import HasTraits, Instance, Int
from traitsui.api import View, Group, Item
from enable.api import ColorTrait
from enable.component_editor import ComponentEditor
import DataframePlotData as dpd
from chaco.api import marker_trait, Plot, ArrayPlotData, AbstractPlotData

class ScatterPlotTraits( HasTraits ):
    plot = Instance( Plot )
    color = ColorTrait( "blue" )
    marker = marker_trait
    marker_size = Int( 4 )

    traits_view = View(
        Group( Item( 'color', label = "Color", style = "custom" ),
               Item( 'marker', label = "Marker" ),
               Item( 'marker_size', label = "Size" ),
               Item( 'plot', editor = ComponentEditor( ), show_label = False ),
               orientation = "vertical" ),
        width = 800, height = 600, resizable = True, title = "Chaco Plot" )

    def __init__(self):
        super( ScatterPlotTraits, self ).__init__( )

        x = linspace( -14, 14, 100 )
コード例 #16
0
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from xdot import *

__all__ = ['WxDotWindow', 'WxDotFrame']

# We need to get the wx version with built-in cairo support
import wxversion
if wxversion.checkInstalled("2.8"):
    wxversion.select("2.8")
else:
    print("wxversion 2.8 is not installed, installed versions are {}".format(
        wxversion.getInstalled()))
import wx
import wx.lib.wxcairo as wxcairo

# This is a crazy hack to get this to work on 64-bit systems
if 'wxMac' in wx.PlatformInfo:
    pass  # Implement if necessary
elif 'wxMSW' in wx.PlatformInfo:
    pass  # Implement if necessary
elif 'wxGTK' in wx.PlatformInfo:
    import ctypes
    gdkLib = wx.lib.wxcairo._findGDKLib()
    gdkLib.gdk_cairo_create.restype = ctypes.c_void_p


class WxDragAction(object):
コード例 #17
0
 u'picker': [0, '', u'picker.py'],
 u'preferences': [0, u'preferences selection', u'preferences.py'],
 u'roman': [0, '', u'roman.py']}

class BoaApp(wx.App):
    def OnInit(self):
        import main_window
        wx.InitAllImageHandlers()
        self.main = main_window.create(None)
        self.main.Show()
        self.SetTopWindow(self.main)
        return True


def main():
    if platform.system() == 'Linux':
        try:
            # to fix some KDE display issues:
            del os.environ['GTK_RC_FILES']
            del os.environ['GTK2_RC_FILES']
        except (ValueError, KeyError):
            pass
    application = BoaApp(0)
    application.MainLoop()

if __name__ == '__main__':
    if 'unicode' not in wx.PlatformInfo:
        print "\nInstalled version: %s\nYou need a unicode build of wxPython to run Metamorphose.\n"%wxversion.getInstalled()
    else:
        main()
コード例 #18
0
import numpy
print('numpy:', numpy.__version__)

import wxversion
print wxversion.getInstalled()
コード例 #19
0
def resolve_wxversion():
    if itrade_config.verbose:
        print 'wxPython Installed :', wxversion.getInstalled()

    # unicode is default after 2.8
    wxversion.select(["2.8-unicode","2.9","3.0"], optionsRequired=True)
コード例 #20
0
import sys

if not hasattr(sys, 'frozen'):
    import wxversion
    print "Wx version: " + str(wxversion.getInstalled())
    wxversion.select('2.8')
import wx

import sys
print "Python version: " + sys.version

class TestWxDrop(wx.Frame):


    def __init__(self, parent):
        '''
        Constructor
        '''
        wx.Frame.__init__(self, parent, title="Test file drop window", size=(400, 200))

        self.SetDropTarget(FileDrop(self))

        self.Show()


class FileDrop (wx.FileDropTarget):
    def __init__(self, window):

        super(FileDrop, self).__init__()
        self.window = window
コード例 #21
0
def resolve_wxversion():
    if itrade_config.verbose:
        print 'wxPython Installed :', wxversion.getInstalled()

    # unicode is default after 2.8
    wxversion.select(["2.8-unicode", "2.9", "3.0"], optionsRequired=True)
コード例 #22
0
    except ImportError:
        version = '2.6'
    else:
        version = None
if version is not None:
    import wxversion
    try:
        ok = wxversion.checkInstalled(version)
    except ValueError:
        ok = False
    if ok:
        wxversion.select(version)
    else:
        import sys
        sys.stderr.write("Invalid wx version: %s\nInstalled versions are: %s\n" % \
                         (version, ', '.join(wxversion.getInstalled())))

_list = list

from event import *
from command import *
from screen import *
from dialog import *
from search import *
from inputfield import *
from form import *
from list import *
from dualform import *
from output import *
from application import *
from configui import *
コード例 #23
0
ファイル: data_stream.py プロジェクト: mdkmdk/datavision
"""
This demo shows how Chaco and Traits can be used to easily build a data
acquisition and visualization system.

Two frames are opened: one has the plot and allows configuration of
various plot properties, and one which simulates controls for the hardware
device from which the data is being acquired; in this case, it is a mockup
random number generator whose mean and standard deviation can be controlled
by the user.
"""

# Major library imports
import random
import wxversion
wxversion.select(filter(lambda x: x.startswith('2'), wxversion.getInstalled()))
wxversion.select( wxversion.getInstalled())
import wx
from numpy import arange, array, hstack, random

# Enthought imports
from enthought.traits.api import Array, Bool, Callable, Enum, Float, HasTraits, \
    Instance, Int, Trait
from enthought.traits.ui.api import Group, HGroup, Item, View, spring, Handler
from enthought.pyface.timer.api import Timer
from traits.api import HasTraits, Instance, Int
# Chaco imports
from enthought.chaco.chaco_plot_editor import ChacoPlotItem


class Viewer( HasTraits ):
    """ This class just contains the two data arrays that will be updated
コード例 #24
0
ファイル: __init__.py プロジェクト: nicLucian/pytis
    except ImportError:
        version = '2.6'
    else:
        version = None
if version is not None:
    import wxversion
    try:
        ok = wxversion.checkInstalled(version)
    except ValueError:
        ok = False
    if ok:
        wxversion.select(version)
    else:
        import sys
        sys.stderr.write("Invalid wx version: %s\nInstalled versions are: %s\n" % \
                         (version, ', '.join(wxversion.getInstalled())))

_list = list

from event import *
from command import *
from screen import *
from dialog import *
from search import *
from inputfield import *
from form import *
from list import *
from dualform import *
from output import *
from application import *
from configui import *
コード例 #25
0
logger = logging.getLogger(__name__)

# This import needs to be before any twisted or dispersy import so it can initalize the reactor in a separate thread
# No need to do reactor.run(), it gets started when imported
from Tribler.Core.Utilities.twisted_thread import reactor, stop_reactor

from Tribler.Main.Utility.utility import initialize_x11_threads
initialize_x11_threads()

# set wxpython version
import wxversion
try:
    # in the windows and mac distribution, there may be no version available.
    # so select a version only when there is any available.
    if wxversion.getInstalled():
        wxversion.select("2.8-unicode")
except wxversion.VersionError:
    logger.exception("Unable to use wxversion installed wxversions: %s",
                     repr(wxversion.getInstalled()))


def run():
    from Tribler.Main.tribler_main import run as run_main
    run_main()


if sys.version_info[:2] != (2, 7):
    print >> sys.stderr, "Tribler needs python 2.7.X to run, current version: %s" % sys.version
    exit(1)
コード例 #26
0
import sys
import os
import threading
import pickle
import pprint
import copy
import StringIO
import colorsys
import time

import wxversion
if wxversion.checkInstalled("2.8"):
    wxversion.select("2.8")
else:
    print("wxversion 2.8 is not installed, installed versions are {}".format(wxversion.getInstalled()))
import wx
import wx.richtext

import textwrap

## this import system (or ros-released) xdot
# import xdot
## need to import currnt package, but not to load this file
# http://stackoverflow.com/questions/6031584/importing-from-builtin-library-when-module-with-same-name-exists
def import_non_local(name, custom_name=None):
    import imp, sys

    custom_name = custom_name or name

    path = filter(lambda x: x != os.path.dirname(os.path.abspath(__file__)), sys.path)
コード例 #27
0
ファイル: PyGCS.py プロジェクト: carloscrespog/PyGCS
#!/usr/bin/python
# Cool stuff
import wxversion
print wxversion.getInstalled()
import wx
import socket
import yaml
import wx.lib.scrolledpanel as scrolled
import wx.lib.agw.floatspin as FS
from random import randrange
import numpy as np
import colorsys
class MyFrame(wx.Frame):
    
    def __init__(self, parent, id, title):
        self.parent=parent

        self.flagOnlyRTCC=True

        self.LRM_IP='192.168.1.200'
        self.LRM_TC_PORT=7131
        self.LRM_TM_PORT=7133
        self.LRM_TLM_PORT=7135
        self.LRM_TLM_TM_PORT=7136

        self.LRM_RTCC_IP='192.168.1.201'
        self.LRM_RTCC_TC_PORT=3333
        self.LRM_RTCC_ACK_PORT=3334
        self.LRM_RTCC_TLM_PORT=3335

        WINDOW_RATIO=4/5.
コード例 #28
0
ファイル: PreferencesGUI.py プロジェクト: pheplex/DESMining
    def __init__(self, parent):
        """
			Constructor.
		"""
        wx.Panel.__init__(self, parent)

        ### FileBrowse
        self.plugin_dir = filebrowse.DirBrowseButton(
            self,
            wx.ID_ANY,
            labelText=_("Plug-ins directory:"),
            toolTip=_("Change the plug-ins directory"),
            dialogTitle=_("Plug-ins directory..."))
        self.domain_dir = filebrowse.DirBrowseButton(
            self,
            wx.ID_ANY,
            labelText=_("Library directory:"),
            toolTip=_("Change the library directory"),
            dialogTitle=_("Libraries directory..."))
        self.out_dir = filebrowse.DirBrowseButton(
            self,
            wx.ID_ANY,
            labelText=_("Output directory:"),
            toolTip=_("Change the output directory"),
            dialogTitle=_("Output directory..."))

        self.plugin_dir.SetValue(PLUGINS_PATH)
        self.domain_dir.SetValue(DOMAIN_PATH)
        self.out_dir.SetValue(OUT_DIR)

        ### StaticText
        self.st1 = wx.StaticText(self, wx.ID_ANY, _("Number of recent file:"))
        self.st2 = wx.StaticText(self, wx.ID_ANY, _("Font size:"))
        self.st3 = wx.StaticText(self, wx.ID_ANY, _("Deep of history item:"))
        self.st4 = wx.StaticText(self, wx.ID_ANY, _("wxPython version:"))

        if wx.VERSION_STRING >= '4.0':
            self.st1.SetToolTipString = self.st1.SetToolTip
            self.st2.SetToolTipString = self.st2.SetToolTip
            self.st3.SetToolTipString = self.st3.SetToolTip
            self.st4.SetToolTipString = self.st4.SetToolTip

        self.st1.SetToolTipString(
            _("Feel free to change the length of list defining the recent opened files."
              ))
        self.st2.SetToolTipString(
            _("Feel free to change the font size of DEVSimpy."))
        self.st3.SetToolTipString(
            _("Feel free to change the number of item for undo/redo command"))
        self.st4.SetToolTipString(
            _("Feel free to change the version of wxpython used loaded by DEVSimPy"
              ))

        ### number of opened file
        self.nb_opened_file = wx.SpinCtrl(self, wx.ID_ANY, '')
        self.nb_opened_file.SetRange(2, 20)
        self.nb_opened_file.SetValue(NB_OPENED_FILE)

        ### Block font size
        self.font_size = wx.SpinCtrl(self, wx.ID_ANY, '')
        self.font_size.SetRange(2, 20)
        self.font_size.SetValue(FONT_SIZE)

        ### number of undo/redo items
        self.nb_history_undo = wx.SpinCtrl(self, wx.ID_ANY, '')
        self.nb_history_undo.SetRange(2, 100)
        self.nb_history_undo.SetValue(NB_HISTORY_UNDO)

        ### CheckBox
        self.cb1 = wx.CheckBox(self, wx.ID_ANY, _('Transparency'))
        if wx.VERSION_STRING >= '4.0':
            self.cb1.SetToolTipString = self.cb1.SetToolTip
        self.cb1.SetToolTipString(
            _("Transparency for the detached frame of diagrams"))
        self.cb1.SetValue(__builtin__.__dict__['TRANSPARENCY'])

        ### wxPython version
        if wx.VERSION_STRING < '4.0':
            import wxversion
            wxv = map(lambda a: a.split('-')[0], wxversion.getInstalled())
        else:
            wxv = [wx.VERSION_STRING]

        self.cb2 = wx.ComboBox(self,
                               wx.ID_ANY,
                               GetWXVersionFromIni(),
                               choices=wxv,
                               style=wx.CB_READONLY)
        if wx.VERSION_STRING >= '4.0':
            self.cb2.SetToolTipString = self.cb2.SetToolTip
        self.cb2.SetToolTipString(_("Default version of wxPython."))
        self.default_wxv = self.cb2.GetValue()

        ### Sizer
        box1 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY,
                                              _('Properties')),
                                 orient=wx.VERTICAL)
        vsizer = wx.BoxSizer(wx.VERTICAL)
        hsizer = wx.GridSizer(4, 2, 20, 20)

        hsizer.AddMany([
            (self.st1, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.nb_opened_file, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st3, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.nb_history_undo, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st2, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.font_size, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st4, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.cb2, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)
        ])

        vsizer.Add(self.plugin_dir, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        vsizer.Add(self.domain_dir, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        vsizer.Add(self.out_dir, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        vsizer.Add(hsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        vsizer.Add(self.cb1, 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        box1.Add(vsizer, 1, wx.EXPAND)

        ### Set sizer
        self.SetSizer(box1)
        self.SetAutoLayout(True)
コード例 #29
0
import sys
import sys

import wx

if not hasattr(sys, 'frozen'):
    import wxversion
    print "Wx version: " + str(wxversion.getInstalled())
    wxversion.select('2.8')

print "Python version: " + sys.version


class TestWxDrop(wx.Frame):
    def __init__(self, parent):
        '''
        Constructor
        '''
        wx.Frame.__init__(self,
                          parent,
                          title="Test file drop window",
                          size=(400, 200))

        self.SetDropTarget(FileDrop(self))

        self.Show()


class FileDrop(wx.FileDropTarget):
    def __init__(self, window):