Table Of Contents

Previous topic

Phoenix Docstrings Guidelines

Next topic

Core Classes

This Page

Phoenix Logo

Core Functions

The functions and macros defined in the Core module are described here: you can look up a function using the alphabetical listing of them.

Function Summary

A | B | C | D | E | F | G | H | I | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y

K

O

  • operator!=
  • operator==

T

Functions



Abort()

Exits the program immediately.

This is a simple wrapper for the standard abort() function which is not available under all platforms (currently only Windows CE doesn’t provide it).

New in version 2.9.4.



AutoBufferedPaintDCFactory(window)

Check if the window is natively float buffered and will return a PaintDC if it is, a BufferedPaintDC otherwise.

It is the caller’s responsibility to delete the DC pointer when finished with it.

Parameters:window (Window) –
Return type: DC


BeginBusyCursor(cursor=HOURGLASS_CURSOR)

Changes the cursor to the given cursor for all windows in the application.

Use EndBusyCursor to revert the cursor back to its previous state. These two calls can be nested, and a counter ensures that only the outer calls take effect.

Parameters:cursor (Cursor) –

See also

IsBusy, BusyCursor



Bell()

Ring the system bell.

Note

This function is categorized as a GUI one and so is not thread-safe.



BitmapFromBuffer(width, height, dataBuffer, alphaBuffer=None)

A compatibility wrapper for Bitmap.FromBuffer and Bitmap.FromBufferAndAlpha

Deprecated since version 3.0.2: Use Bitmap.FromBuffer or Bitmap.FromBufferAndAlpha instead.



BitmapFromBufferRGBA(width, height, dataBuffer)

A compatibility wrapper for Bitmap.FromBufferRGBA

Deprecated since version 3.0.2: Use Bitmap.FromBufferRGBA instead.



BitmapFromImage(image)

A compatibility wrapper for the wx.Bitmap(wx.Image) constructor

Deprecated since version 3.0.2: Use Bitmap instead



CallAfter(callableObj, *args, **kw)

Call the specified function after the current and pending event handlers have been completed. This is also good for making GUI method calls from non-GUI threads. Any extra positional or keyword args are passed on to the callable when it is called.

Parameters:
  • callableObj (PyObject) – the callable object
  • args – arguments to be passed to the callable object
  • kw – keywords to be passed to the callable object

See also

CallLater


contributed Contributed Examples:

Example 1 - Andrea Gavana (download):

#!/usr/bin/env python

# This sample shows hot to take advantage of wx.CallAfter when running a
# separate thread and updating the GUI in the main thread

import wx
import threading
import time

class MainFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='CallAfter example')

        panel = wx.Panel(self)
        self.label = wx.StaticText(panel, label="Ready")
        self.btn = wx.Button(panel, label="Start")
        self.gauge = wx.Gauge(panel)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.btn, proportion=0, flag=wx.EXPAND)
        sizer.Add(self.gauge, proportion=0, flag=wx.EXPAND)

        panel.SetSizerAndFit(sizer)
        self.Bind(wx.EVT_BUTTON, self.OnButton)

    def OnButton(self, event):
        """ This event handler starts the separate thread. """
        self.btn.Enable(False)
        self.gauge.SetValue(0)
        self.label.SetLabel("Running")

        thread = threading.Thread(target=self.LongRunning)
        thread.start()

    def OnLongRunDone(self):
        self.gauge.SetValue(100)
        self.label.SetLabel("Done")
        self.btn.Enable(True)

    def LongRunning(self):
        """This runs in a different thread.  Sleep is used to
         simulate a long running task."""
        time.sleep(3)
        wx.CallAfter(self.gauge.SetValue, 20)
        time.sleep(5)
        wx.CallAfter(self.gauge.SetValue, 70)
        time.sleep(4)
        wx.CallAfter(self.OnLongRunDone)

if __name__ == "__main__":
    app = wx.App(0)
    frame = MainFrame(None)
    frame.Show()
    app.MainLoop()



ClientDisplayRect()

Returns the dimensions of the work area on the display.

This is the same as GetClientDisplayRect but allows to retrieve the individual components instead of the entire rectangle.

Any of the output pointers can be None if the corresponding value is not needed by the caller.

Return type:tuple
Returns:( x, y, width, height )

See also

Display



ColourDisplay()

Returns True if the display is colour, False otherwise.

Return type:bool


date2pydate(date)

Convert a DateTime object to a Python datetime.



DateTimeFromDMY(day, month, year=DateTime.Inv_Year, hour=0, minute=0, second=0, millisecond=0)

Compatibility wrapper for DateTime.FromDMY

Deprecated since version 3.0.2: Use DateTime.FromDMY instead.



DateTimeFromHMS(hour, minute=0, second=0, millisecond=0)

Compatibility wrapper for DateTime.FromHMS

Deprecated since version 3.0.2: Use DateTime.FromHMS instead.



DateTimeFromJDN(jdn)

Compatibility wrapper for DateTime.FromJDN

Deprecated since version 3.0.2: Use DateTime.FromJDN instead.



DateTimeFromTimeT(timet)

Compatibility wrapper for DateTime.FromTimeT

Deprecated since version 3.0.2: Use DateTime.FromTimeT instead.



DirSelector(message=DirSelectorPromptStr, default_path="", style=0, pos=DefaultPosition, parent=None)

Pops up a directory selector dialog.

The arguments have the same meaning as those of DirDialog.__init__ . The message is displayed at the top, and the default_path, if specified, is set as the initial selection.

The application must check for an empty return value (if the user pressed Cancel). For example:

selector = wx.DirSelector("Choose a folder")
if selector.strip():
    # Do something with the folder name
    print selector
Parameters:
  • message (string) –
  • default_path (string) –
  • style (long) –
  • pos (Point) –
  • parent (Window) –
Return type:

string



DisableAsserts()

Disable the condition checks in the assertions.

This is the same as calling SetAssertHandler with None handler.

New in version 2.9.0.



DisplayDepth()

Returns the depth of the display (a value of 1 denotes a monochrome display).

Return type:int


DisplaySize()

Returns the display size in pixels.

Either of output pointers can be None if the caller is not interested in the corresponding value.

Return type:tuple
Returns:( width, height )


DisplaySizeMM()

Returns the display size in millimeters.

Either of output pointers can be None if the caller is not interested in the corresponding value.

Return type:tuple
Returns:( width, height )


EmptyBitmap(width, height, depth=BITMAP_SCREEN_DEPTH)

A compatibility wrapper for the wx.Bitmap(width, height, depth) constructor

Deprecated since version 3.0.2: Use Bitmap instead



EmptyBitmapRGBA(width, height, red=0, green=0, blue=0, alpha=0)

A compatibility wrapper for Bitmap.FromRGBA

Deprecated since version 3.0.2: Use Bitmap.FromRGBA instead.



EmptyIcon()

A compatibility wrapper for the Icon constructor

Deprecated since version 3.0.2: Use Icon instead



EmptyImage(width=0, height=0, clear=True)

A compatibility wrapper for the wx.Image(width, height) constructor

Deprecated since version 3.0.2: Use Image instead.



EnableTopLevelWindows(enable=True)

This function enables or disables all top level windows.

It is used by SafeYield.

Parameters:enable (bool) –


EndBusyCursor()

Changes the cursor back to the original cursor, for all windows in the application.

Use with BeginBusyCursor.

See also

IsBusy, BusyCursor



Execute(command, flags=EXEC_ASYNC, callback=None, env=None)

Executes another program in Unix or Windows.

In the overloaded versions of this function, if flags parameter contains EXEC_ASYNC flag (the default), flow of control immediately returns. If it contains EXEC_SYNC , the current application waits until the other program has terminated.

In the case of synchronous execution, the return value is the exit code of the process (which terminates by the moment the function returns) and will be -1 if the process couldn’t be started and typically 0 if the process terminated successfully. Also, while waiting for the process to terminate, Execute will call Yield. Because of this, by default this function disables all application windows to avoid unexpected reentrancies which could result from the users interaction with the program while the child process is running. If you are sure that it is safe to not disable the program windows, you may pass EXEC_NODISABLE flag to prevent this automatic disabling from happening.

For asynchronous execution, however, the return value is the process id and zero value indicates that the command could not be executed. As an added complication, the return value of -1 in this case indicates that we didn’t launch a new process, but connected to the running one (this can only happen when using DDE under Windows for command execution). In particular, in this case only, the calling code will not get the notification about process termination.

If callback isn’t None and if execution is asynchronous, Process.OnTerminate will be called when the process finishes. Specifying this parameter also allows you to redirect the standard input and/or output of the process being launched by calling Process.Redirect .

Under Windows, when launching a console process its console is shown by default but hidden if its IO is redirected. Both of these default behaviours may be overridden: if EXEC_HIDE_CONSOLE is specified, the console will never be shown. If EXEC_SHOW_CONSOLE is used, the console will be shown even if the child process IO is redirected. Neither of these flags affect non-console Windows applications or does anything under the other systems.

Under Unix the flag EXEC_MAKE_GROUP_LEADER may be used to ensure that the new process is a group leader (this will create a new session if needed). Calling Kill passing KILL_CHILDREN will kill this process as well as all of its children (except those which have started their own session). Under MSW, this flag can be used with console processes only and corresponds to the native CREATE_NEW_PROCESS_GROUP flag.

The EXEC_NOEVENTS flag prevents processing of any events from taking place while the child process is running. It should be only used for very short-lived processes as otherwise the application windows risk becoming unresponsive from the users point of view. As this flag only makes sense with EXEC_SYNC , EXEC_BLOCK equal to the sum of both of these flags is provided as a convenience.

Parameters:
  • command (string) – The command to execute and any parameters to pass to it as a single string, i.e. “emacs file.txt”.
  • flags (int) – Must include either EXEC_ASYNC or EXEC_SYNC and can also include EXEC_SHOW_CONSOLE, EXEC_HIDE_CONSOLE, EXEC_MAKE_GROUP_LEADER (in either case) or EXEC_NODISABLE and EXEC_NOEVENTS or EXEC_BLOCK, which is equal to their combination, in EXEC_SYNC case.
  • callback (Process) – An optional pointer to Process.
  • env (ExecuteEnv) – An optional pointer to additional parameters for the child process, such as its initial working directory and environment variables. This parameter is available in wxWidgets 2.9.2 and later only.
Return type:

long


contributed Contributed Examples:

Example 1 - Andrea Gavana (download):

#!/usr/bin/env python

# This sample demonstrates a simple use of wx.Process/wx.Execute to
# monitor an external program stdout

import wx

class ProcessFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='Process/Execute example')

        panel = wx.Panel(self)
        self.label = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        self.btn = wx.Button(panel, label="Start")

        self.process = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.btn, proportion=0, flag=wx.EXPAND)

        panel.SetSizerAndFit(sizer)
        self.Bind(wx.EVT_BUTTON, self.OnButton)

        self.Bind(wx.EVT_IDLE, self.OnIdle)
        self.Bind(wx.EVT_END_PROCESS, self.OnProcessEnded)
        
    def OnButton(self, event):
        self.btn.Enable(False)
        self.label.SetValue('')
        self.LongRunning()

    def LongRunning(self):
        """
        This runs in the GUI thread but uses wx.Process and
        wx.Execute to start and monitor a separate process.
        """

        cmd = 'python -u external_program.py'

        self.process = wx.Process(self)
        self.process.Redirect()

        wx.Execute(cmd, wx.EXEC_ASYNC, self.process)

    def OnIdle(self, event):
        """ This event handler catches the process stdout. """

        if self.process is not None:
            stream = self.process.GetInputStream()
            if stream.CanRead():
                text = stream.read()
                self.label.AppendText(text)

    def OnProcessEnded(self, event):

        stream = self.process.GetInputStream()

        if stream.CanRead():
            text = stream.read()
            self.label.AppendText(text)

        self.btn.Enable(True)
        self.label.AppendText('Finished')


if __name__ == "__main__":
    app = wx.App(0)
    frame = ProcessFrame(None)
    frame.Show()
    app.MainLoop()



Exit()

Exits application after calling App.OnExit .

Should only be used in an emergency: normally the top-level frame should be deleted (after deleting all other frames) to terminate the application. See CloseEvent and App.



FFont(pointSize, family, flags=FONTFLAG_DEFAULT, faceName="", encoding=FONTENCODING_DEFAULT)


FileSelector(message, default_path="", default_filename="", default_extension="", wildcard=FileSelectorDefaultWildcardStr, flags=0, parent=None, x=DefaultCoord, y=DefaultCoord)

Pops up a file selector box.

In Windows, this is the common file selector dialog. In X, this is a file selector box with the same functionality. The path and filename are distinct elements of a full file pathname. If path is empty, the current directory will be used. If filename is empty, no default filename will be supplied. The wildcard determines what files are displayed in the file selector, and file extension supplies a type extension for the required filename. Flags may be a combination of FD_OPEN, FD_SAVE, FD_OVERWRITE_PROMPT or FD_FILE_MUST_EXIST.

Both the Unix and Windows versions implement a wildcard filter. Typing a filename containing wildcards (, ?) in the filename text item, and clicking on Ok, will result in only those files matching the pattern being displayed.

The wildcard may be a specification for multiple types of file with a description for each, such as:

wildcard = "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif"

The application must check for an empty return value (the user pressed Cancel). For example:

filename = wx.FileSelector("Choose a file to open")

if filename.strip():
    # work with the file
    print filename

# else: cancelled by user
Parameters:
  • message (string) –
  • default_path (string) –
  • default_filename (string) –
  • default_extension (string) –
  • wildcard (string) –
  • flags (int) –
  • parent (Window) –
  • x (int) –
  • y (int) –
Return type:

string

Note

FD_MULTIPLE can only be used with FileDialog and not here since this function only returns a single file name.



FileSelectorEx(message=FileSelectorPromptStr, default_path="", default_filename="", indexDefaultExtension=None, wildcard=FileSelectorDefaultWildcardStr, flags=0, parent=None, x=DefaultCoord, y=DefaultCoord)

An extended version of FileSelector.

Parameters:
  • message (string) –
  • default_path (string) –
  • default_filename (string) –
  • indexDefaultExtension (int) –
  • wildcard (string) –
  • flags (int) –
  • parent (Window) –
  • x (int) –
  • y (int) –
Return type:

string



FindMenuItemId(frame, menuString, itemString)

Find a menu item identifier associated with the given frame’s menu bar.

Parameters:
  • frame (Frame) –
  • menuString (string) –
  • itemString (string) –
Return type:

int



FindWindowAtPoint(pt)

Find the deepest window at the given mouse position in screen coordinates, returning the window if found, or None if not.

This function takes child windows at the given position into account even if they are disabled. The hidden children are however skipped by it.

Parameters:pt (Point) –
Return type: Window


FindWindowAtPointer()

Find the deepest window at the mouse pointer position, returning the window and current pointer position in screen coordinates.

Return type:tuple
Returns:( Window, pt )


FindWindowById(id, parent=None)

FindWindowById(id, parent=None) . Window

Find the first window in the application with the given id. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases.

Return type: Window


FindWindowByLabel(label, parent=None)

Find a window by its label. Depending on the type of window, the label may be a window title or panel item label. If parent is None, the search will start from all top-level frames and dialog boxes; if not None, the search will be limited to the given window hierarchy. The search is recursive in both cases.

Parameters:
  • label (string) –
  • parent (Window) –
Return type:

Window

Deprecated since version 3.0.2: Replaced by Window.FindWindowByLabel .



FindWindowByName(name, parent=None)

Find a window by its name (as given in a window constructor or Create function call). If parent is None, the search will start from all top-level frames and dialog boxes; if not None, the search will be limited to the given window hierarchy. The search is recursive in both cases.

If no such named window is found, FindWindowByLabel is called.

Parameters:
  • name (string) –
  • parent (Window) –
Return type:

Window

Deprecated since version 3.0.2: Replaced by Window.FindWindowByName .



GetAccelFromString(label)

Deprecated since version 3.0.2.



GetActiveWindow()

Gets the currently active window (implemented for MSW and GTK only currently, always returns None in the other ports).

Return type: Window


GetApp()

Returns the current application object.

Return type: PyApp


GetBatteryState()

Returns battery state as one of BATTERY_NORMAL_STATE , BATTERY_LOW_STATE , BATTERY_CRITICAL_STATE , BATTERY_SHUTDOWN_STATE or BATTERY_UNKNOWN_STATE .

BATTERY_UNKNOWN_STATE is also the default on platforms where this feature is not implemented (currently everywhere but MS Windows).
Return type: BatteryState


GetClientDisplayRect()

Returns the dimensions of the work area on the display.

On Windows this means the area not covered by the taskbar, etc. Other platforms are currently defaulting to the whole display until a way is found to provide this info for all window managers, etc.

Return type: Rect

See also

Display



GetColourFromUser(parent, colInit, caption="", data=None)

Shows the colour selection dialog and returns the colour selected by user or invalid colour (use Colour.IsOk to test whether a colour is valid) if the dialog was cancelled.

Parameters:
  • parent (Window) – The parent window for the colour selection dialog.
  • colInit (Colour) – If given, this will be the colour initially selected in the dialog.
  • caption (string) – If given, this will be used for the dialog caption.
  • data (ColourData) – Optional object storing additional colour dialog settings, such as custom colours. If none is provided the same settings as the last time are used.
Return type:

Colour



GetDisplayPPI()

Returns the display resolution in pixels per inch.

The x component of the returned Size object contains the horizontal resolution and the y one

Return type: Size

New in version 2.9.0.

See also

Display



GetDisplaySize()

Returns the display size in pixels.

Return type: Size

See also

Display



GetDisplaySizeMM()

Returns the display size in millimeters.

Return type: Size

See also

Display



GetEmailAddress(*args, **kw)

Copies the user’s email address into the supplied buffer, by concatenating the values returned by GetFullHostName and GetUserId.

Returns:True if successful, False otherwise.


GetFontFromUser(parent, fontInit, caption="")

Shows the font selection dialog and returns the font selected by user or invalid font (use Font.IsOk to test whether a font is valid) if the dialog was cancelled.

Parameters:
  • parent (Window) – The parent window for the font selection dialog.
  • fontInit (Font) – If given, this will be the font initially selected in the dialog.
  • caption (string) – If given, this will be used for the dialog caption.
Return type:

Font



GetFullHostName()

Returns the FQDN (fully qualified domain host name) or an empty string on error.

Return type:string

See also

GetHostName



GetHomeDir()

Return the (current) user’s home directory.

Return type:string


GetHostName(*args, **kw)

Copies the current host machine’s name into the supplied buffer.

Please note that the returned name is not fully qualified, i.e. it does not include the domain name.

Under Windows or NT, this function first looks in the environment variable SYSTEM_NAME; if this is not found, the entry HostName in the wxWidgets section of the WIN.INI file is tried.

Returns:The hostname if successful or an empty string otherwise.

See also

GetFullHostName



GetKeyState(key)

For normal keys, returns True if the specified key is currently down.

For togglable keys (Caps Lock, Num Lock and Scroll Lock), returns True if the key is toggled such that its LED indicator is lit. There is currently no way to test whether togglable keys are up or down.

Even though there are virtual key codes defined for mouse buttons, they cannot be used with this function currently.

Parameters:key (KeyCode) –
Return type:bool


GetLibraryVersionInfo()

Get wxWidgets version information.

Return type: VersionInfo

New in version 2.9.2.

See also

VersionInfo



GetMousePosition()

Returns the mouse position in screen coordinates.

Return type: Point


GetMouseState()

Returns the current state of the mouse.

Returns a MouseState instance that contains the current position of the mouse pointer in screen coordinates, as well as boolean values indicating the up/down status of the mouse buttons and the modifier keys.

Return type: MouseState


GetOsDescription()

Returns the string containing the description of the current platform in a user-readable form.

For example, this function may return strings like “Windows NT Version 4.0” or “Linux 2.2.2 i386”.

Return type:string

See also

GetOsVersion



GetOsVersion()

Gets the version and the operating system ID for currently running OS.

The returned OperatingSystemId value can be used for a basic categorization of the OS family; the major and minor version numbers allows to detect a specific system.

For Unix-like systems ( OS_UNIX ) the major and minor version integers will contain the kernel major and minor version numbers (as returned by the ‘uname -r’ command); e.g. “2” and “6” if the machine is using kernel 2.6.19.

For Mac OS X systems ( OS_MAC ) the major and minor version integers are the natural version numbers associated with the OS; e.g. “10” and “6” if the machine is using Mac OS X Snow Leopard.

For Windows-like systems ( OS_WINDOWS ) the major and minor version integers will contain the following values:

Windows OS name Major version Minor version
Windows 7 6 1
Windows Server 2008 R2 6 1
Windows Server 2008 6 0
Windows Vista 6 0
Windows Server 2003 R2 5 2
Windows Server 2003 5 2
Windows XP 5 1
Windows 2000 5 0

See the`MSDN <http://msdn.microsoft.com/en-us/library/ms724832(VS.85).aspx>`_ for more info about the values above.

Return type:tuple
Returns:( OperatingSystemId, major, minor )


GetPasswordFromUser(message, caption=GetPasswordFromUserPromptStr, default_value="", parent=None, x=DefaultCoord, y=DefaultCoord, centre=True)

Similar to GetTextFromUser but the text entered in the dialog is not shown on screen but replaced with stars.

This is intended to be used for entering passwords as the function name implies.

Parameters:
  • message (string) –
  • caption (string) –
  • default_value (string) –
  • parent (Window) –
  • x (int) –
  • y (int) –
  • centre (bool) –
Return type:

string



GetPowerType()

Returns the type of power source as one of POWER_SOCKET , POWER_BATTERY or POWER_UNKNOWN .

POWER_UNKNOWN is also the default on platforms where this feature is not implemented (currently everywhere but MS Windows).
Return type: PowerType


GetProcessId()

Returns the number uniquely identifying the current process in the system.

If an error occurs, 0 is returned.

Return type:int


GetSingleChoice(*args, **kw)

overload Overloaded Implementations:



GetSingleChoice (message, caption, aChoices, parent=None, x=DefaultCoord, y=DefaultCoord, centre=True, width=CHOICE_WIDTH, height=CHOICE_HEIGHT, initialSelection=0)

Pops up a dialog box containing a message, OK/Cancel buttons and a single-selection listbox.

The user may choose an item and press OK to return a string or Cancel to return the empty string. Use GetSingleChoiceIndex if empty string is a valid choice and if you want to be able to detect pressing Cancel reliably.

You may pass the list of strings to choose from either using choices which is an array of n strings for the listbox or by using a single aChoices parameter of type [].

If centre is True, the message text (which may include new line characters) is centred; if False, the message is left-justified.



GetSingleChoice (message, caption, choices, initialSelection, parent=None)

Parameters:
  • message (string) –
  • caption (string) –
  • choices (list of strings) –
  • initialSelection (int) –
  • parent (Window) –
Return type:

string





GetTextFromUser(message, caption=GetTextFromUserPromptStr, default_value="", parent=None, x=DefaultCoord, y=DefaultCoord, centre=True)

Pop up a dialog box with title set to caption, message , and a default_value .

The user may type in text and press OK to return this text, or press Cancel to return the empty string.

If centre is True, the message text (which may include new line characters) is centred; if False, the message is left-justified.

This function is a wrapper around TextEntryDialog and while it is usually more convenient to use, using the dialog directly is more flexible, e.g. it allows you to specify the TE_MULTILINE to allow the user enter multiple lines of text while this function is limited to single line entry only.

Parameters:
  • message (string) –
  • caption (string) –
  • default_value (string) –
  • parent (Window) –
  • x (int) –
  • y (int) –
  • centre (bool) –
Return type:

string



GetTopLevelParent(window)

Returns the first top level parent of the given window, or in other words, the frame or dialog containing it, or None.

Parameters:window (Window) –
Return type: Window


GetTopLevelWindows()

Returns a list-like object of the the application’s top-level windows, (frames,dialogs, etc.)

Return type:WindowList


GetTranslation(*args, **kw)

overload Overloaded Implementations:



GetTranslation (string, domain=””)

This function returns the translation of string in the current locale() .

If the string is not found in any of the loaded message catalogs (see Internationalization), the original string is returned. In debug build, an error message is logged domain is specified then only that domain/catalog is searched for a matching string. As this function is used very often, an alternative (and also common in Unix world) syntax is provided: the _ macro is defined to do the same thing as GetTranslation.

This function is thread-safe.

Parameters:
  • string (string) –
  • domain (string) –
Return type:

string

Note

This function is not suitable for literal strings in Unicode builds since the literal strings must be enclosed in T macro which makes them unrecognised by xgettext , and so they are not extracted to the message catalog. Instead, use the _ and PLURAL macro for all literal strings.

See also

GetTranslation



GetTranslation (string, plural, n, domain=””)

This is an overloaded version of GetTranslation, please see its documentation for general information.

This version is used when retrieving translation of string that has different singular and plural forms in English or different plural forms in some other language. Like GetTranslation, the string parameter must contain the singular form of the string to be converted and is used as the key for the search in the catalog. The plural parameter is the plural form (in English). The parameter n is used to determine the plural form. If no message catalog is found, string is returned if “n == 1”, otherwise plural is returned.

See GNU gettext Manual for additional information on plural forms handling: http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms For a shorter alternative see the PLURAL macro.

This function is thread-safe.

Parameters:
  • string (string) –
  • plural (string) –
  • n
  • domain (string) –
Return type:

string





GetUserHome(user="")

Returns the home directory for the given user.

If the user is empty (default value), this function behaves like GetHomeDir (i.e. returns the current user home directory).

If the home directory couldn’t be determined, an empty string is returned.

Parameters:user (string) –
Return type:string


GetUserId(*args, **kw)

This function returns the “user id” also known as “login name” under Unix (i.e.

something like “jsmith”). It uniquely identifies the current user (on this system). Under Windows or NT, this function first looks in the environment variables USER and LOGNAME; if neither of these is found, the entry UserId in the wxWidgets section of the WIN.INI file is tried.

Returns:The login name if successful or an empty string otherwise.

See also

GetUserName



GetUserName(*args, **kw)

This function returns the full user name (something like “Mr. John Smith”).

Under Windows or NT, this function looks for the entry UserName in the wxWidgets section of the WIN.INI file. If PenWindows is running, the entry Current in the section User of the PENWIN.INI file is used.

Returns:The full user name if successful or an empty string otherwise.

See also

GetUserId



HandleFatalExceptions(doIt=True)

If doIt is True, the fatal exceptions (also known as general protection faults under Windows or segmentation violations in the Unix world) will be caught and passed to App.OnFatalException .

By default, i.e. before this function is called, they will be handled in the normal way which usually just means that the application will be terminated. Calling HandleFatalExceptions with doIt equal to False will restore this default behaviour.

Notice that this function is only available if USE_ON_FATAL_EXCEPTION is 1 and under Windows platform this requires a compiler with support for SEH (structured exception handling) which currently means only Microsoft Visual C++ or a recent Borland C++ version.

Parameters:doIt (bool) –
Return type:bool


ImageFromBitmap(bitmap)

Create a Image from a Bitmap

Deprecated since version 3.0.2: Use bitmap.ConvertToImage instead.



ImageFromBuffer(width, height, dataBuffer, alphaBuffer=None)

Creates a Image from the data in dataBuffer. The dataBuffer parameter must be a Python object that implements the buffer interface, such as a string, array, etc. The dataBuffer object is expected to contain a series of RGB bytes and be width*height*3 bytes long. A buffer object can optionally be supplied for the image’s alpha channel data, and it is expected to be width*height bytes long.

The Image will be created with its data and alpha pointers initialized to the memory address pointed to by the buffer objects, thus saving the time needed to copy the image data from the buffer object to the Image. While this has advantages, it also has the shoot-yourself-in-the-foot risks associated with sharing a C pointer between two objects.

To help alleviate the risk a reference to the data and alpha buffer objects are kept with the Image, so that they won’t get deleted until after the wx.Image is deleted. However please be aware that it is not guaranteed that an object won’t move its memory buffer to a new location when it needs to resize its contents. If that happens then the Image will end up referring to an invalid memory location and could cause the application to crash. Therefore care should be taken to not manipulate the objects used for the data and alpha buffers in a way that would cause them to change size.



ImageFromData(width, height, data)

Compatibility wrapper for creating an image from RGB data

Deprecated since version 3.0.2: Use Image instead.



ImageFromDataWithAlpha(width, height, data, alpha)

Compatibility wrapper for creating an image from RGB and Alpha data

Deprecated since version 3.0.2: Use Image instead.



ImageFromStream(stream, type=BITMAP_TYPE_ANY, index=-1)

Load an image from a stream (file-like object)

Deprecated since version 3.0.2: Use Image instead.



InfoMessageBox(parent)

Shows a message box with the information about the wxWidgets build used, including its version, most important build parameters and the version of the underlying GUI toolkit.

This is mainly used for diagnostic purposes and can be invoked by Ctrl-Alt-middle clicking on any Window which doesn’t otherwise handle this event.

Parameters:parent (Window) –

New in version 2.9.0.



InitAllImageHandlers()

Initializes all available image handlers.

This function calls Image.AddHandler for all the available image handlers (see Available image handlers for the full list). Calling it is the simplest way to initialize Image but it creates and registers even the handlers your program may not use. If you want to avoid the overhead of doing this you need to call Image.AddHandler manually just for the handlers that you do want to use.



IntersectRect(r1, r2)
Calculate and return the intersection of r1 and r2. Returns None if there is no intersection.
Return type:PyObject


IsBusy()

Returns True if between two BeginBusyCursor and EndBusyCursor calls.

Return type:bool

See also

BusyCursor.



IsDragResultOk(res)

Returns True if res indicates that something was done during a DnD operation, i.e.

is neither error nor none nor cancel.

Parameters:res (DragResult) –
Return type:bool


IsMainThread()

Returns True if the current thread is what considers the GUI thread.

Return type:bool


IsPlatform64Bit()

Returns True if the operating system the program is running under is 64 bit.

The check is performed at run-time and may differ from the value available at compile-time (at compile-time you can just check if sizeof(void*) == 8 ) since the program could be running in emulation mode or in a mixed 32/64 bit system (bi-architecture operating system).

Return type:bool

Note

This function is not 100% reliable on some systems given the fact that there isn’t always a standard way to do a reliable check on the OS architecture.



IsPlatformLittleEndian()

Returns True if the current platform is little endian (instead of big endian).

The check is performed at run-time.

Return type:bool


Kill(pid, sig=SIGTERM, rc=None, flags=KILL_NOCHILDREN)

Equivalent to the Unix kill function: send the given signal sig to the process with PID pid.

The valid signal values are:

           # Signal enumeration

           wx.SIGNONE  # verify if the process exists under Unix
           wx.SIGHUP
           wx.SIGINT
           wx.SIGQUIT
           wx.SIGILL
           wx.SIGTRAP
           wx.SIGABRT
           wx.SIGEMT
           wx.SIGFPE
           wx.SIGKILL  # forcefully kill, dangerous!
           wx.SIGBUS
           wx.SIGSEGV
           wx.SIGSYS
           wx.SIGPIPE
           wx.SIGALRM
           wx.SIGTERM  # terminate the process gently



``SIGNONE`` ,   ``SIGKILL``   and   ``SIGTERM``   have the same meaning under both Unix and Windows but all the other signals are equivalent to   ``SIGTERM``   under Windows. Moreover, under Windows,   ``SIGTERM``   is implemented by posting a message to the application window, so it only works if the application does have windows. If it doesn't, as is notably always the case for the console applications, you need to use   ``SIGKILL``   to actually kill the process. Of course, this doesn't allow the process to shut down gracefully and so should be avoided if possible.

Returns 0 on success, -1 on failure. If the rc parameter is not None, it will be filled with a value from the KillError enum:

# KillError enumeration

wx.KILL_OK             # no error
wx.KILL_BAD_SIGNAL     # no such signal
wx.KILL_ACCESS_DENIED  # permission denied
wx.KILL_NO_PROCESS     # no such process
wx.KILL_ERROR          # another, unspecified error

The flags parameter can be KILL_NOCHILDREN (the default), or KILL_CHILDREN, in which case the child processes of this process will be killed too. Note that under Unix, for KILL_CHILDREN to work you should have created the process by passing EXEC_MAKE_GROUP_LEADER to Execute.

Parameters:
Return type:

int



LaunchDefaultApplication(document, flags=0)

Opens the document in the application associated with the files of this type.

The flags parameter is currently not used

Returns True if the application was successfully launched.

Parameters:
  • document (string) –
  • flags (int) –
Return type:

bool



LaunchDefaultBrowser(url, flags=0)

Opens the url in user’s default browser.

If the flags parameter contains BROWSER_NEW_WINDOW flag, a new window is opened for the URL (currently this is only supported under Windows).

And unless the flags parameter contains BROWSER_NOBUSYCURSOR flag, a busy cursor is shown while the browser is being launched (using BusyCursor).

The parameter url is interpreted as follows:

  • if it has a valid scheme (e.g. "file:" , "http:" or "mailto:" ) it is passed to the appropriate browser configured in the user system.
  • if it has no valid scheme (e.g. it’s a local file path without the "file:" prefix), then FileExists and DirExists are used to test if it’s a local file/directory; if it is, then the browser is called with the url parameter eventually prefixed by "file:" .
  • if it has no valid scheme and it’s not a local file/directory, then "http:" is prepended and the browser is called.

Returns True if the application was successfully launched.

Parameters:
  • url (string) –
  • flags (int) –
Return type:

bool

Note

For some configurations of the running user, the application which is launched to open the given URL may be URL-dependent (e.g. a browser may be used for local URLs while another one may be used for remote URLs).



LoadFileSelector(what, extension, default_name="", parent=None)

Ask for filename to load.

Parameters:
  • what (string) –
  • extension (string) –
  • default_name (string) –
  • parent (Window) –
Return type:

string



LogDebug(message)

The right functions for debug output.

They only do something in debug mode (when the preprocessor symbol WXDEBUG is defined) and expand to nothing in release mode (otherwise).

Parameters:message (string) –


LogError(message)

The functions to use for error messages, i.e.

the messages that must be shown to the user. The default processing is to pop up a message box to inform the user about it.

Parameters:message (string) –


LogFatalError(message)

Like LogError, but also terminates the program with the exit code 3.

Using abort() standard function also terminates the program with this exit code.

Parameters:message (string) –


LogGeneric(level, message)

Logs a message with the given LogLevel.

E.g. using LOG_Message as first argument, this function behaves like LogMessage.

Parameters:
  • level (LogLevel) –
  • message (string) –


LogMessage(message)

For all normal, informational messages.

They also appear in a message box by default (but it can be changed).

Parameters:message (string) –


LogStatus(*args, **kw)

overload Overloaded Implementations:



LogStatus (frame, message)

Messages logged by this function will appear in the statusbar of the frame or of the top level application window by default (i.e.

when using the second version of the functions).

If the target frame doesn’t have a statusbar, the message will be lost.

Parameters:
  • frame (Frame) –
  • message (string) –



LogStatus (message)

Parameters:message (string) –





LogSysError(message)

Mostly used by wxWidgets itself, but might be handy for logging errors after system call (API function) failure.

It logs the specified message text as well as the last system error code (errno or GetLastError() depending on the platform) and the corresponding error message. The second form of this function takes the error code explicitly as the first argument.

Parameters:message (string) –


LogVerbose(message)

For verbose output.

Normally, it is suppressed, but might be activated if the user wishes to know more details about the program progress (another, but possibly confusing name for the same function could be LogInfo ).

Parameters:message (string) –


LogWarning(message)

For warnings - they are also normally shown to the user, but don’t interrupt the program work.

Parameters:message (string) –


MacThemeColour(themeBrushID)
Return type: Colour


MessageBox(message, caption=MessageBoxCaptionStr, style=OK|CENTRE, parent=None, x=DefaultCoord, y=DefaultCoord)

Show a general purpose message dialog.

This is a convenient function which is usually used instead of using MessageDialog directly. Notice however that some of the features, such as extended text and custom labels for the message box buttons, are not provided by this function but only by MessageDialog.

The return value is one of: YES , NO , CANCEL , OK or HELP (notice that this return value is different from the return value of MessageDialog.ShowModal ).

For example:

answer = wx.MessageBox("Quit program?", "Confirm",
                       wx.YES_NO | wx.CANCEL, main_frame)
if answer == wx.YES:
    main_frame.Close()

message may contain newline characters, in which case the message will be split into separate lines, to cater for large messages.

Parameters:
  • message (string) – Message to show in the dialog.
  • caption (string) – The dialog title.
  • style (int) – Combination of style flags described in MessageDialog documentation.
  • parent (Window) – Parent window.
  • x (int) – Horizontal dialog position (ignored under MSW). Use DefaultCoord for x and y to let the system position the window.
  • y (int) – Vertical dialog position (ignored under MSW).
Return type:

int



MicroSleep(microseconds)

Sleeps for the specified number of microseconds.

The microsecond resolution may not, in fact, be available on all platforms (currently only Unix platforms with nanosleep(2) may provide it) in which case this is the same as calling MilliSleep with the argument of microseconds/1000.

Parameters:microseconds (long) –


MilliSleep(milliseconds)

Sleeps for the specified number of milliseconds.

Notice that usage of this function is encouraged instead of calling usleep(3) directly because the standard usleep() function is not MT safe.

Parameters:milliseconds (long) –


NewEventType()

Generates a new unique event type.

Usually this function is only used by DEFINE_EVENT and not called directly.

Return type:EventType


NewId()

Generates an integer identifier unique to this run of the program.

Return type:int

Deprecated since version 3.0.2: Ids generated by it can conflict with the Ids defined by the user code, use ID_ANY to assign ids which are guaranteed to not conflict with the user-defined ids for the controls and menu items you create instead of using this function.



Now()

Returns a string representing the current date and time.

Return type:string


operator!=
Parameters:


operator==
Parameters:


PostEvent(dest, event)

In a GUI application, this function posts event to the specified dest object using EvtHandler.AddPendingEvent .

Otherwise, it dispatches event immediately using EvtHandler.ProcessEvent . See the respective documentation for details (and caveats). Because of limitation of EvtHandler.AddPendingEvent this function is not thread-safe for event objects having String fields, use QueueEvent instead.

Parameters:


pydate2wxdate(date)

Convert a Python date or datetime to a DateTime object



QueueEvent(dest, event)

Queue an event for processing on the given object.

This is a wrapper around EvtHandler.QueueEvent , see its documentation for more details.

Parameters:
  • dest (EvtHandler) – The object to queue the event on, can’t be NULL .
  • event (Event) – The heap-allocated and non- NULL event to queue, the function takes ownership of it.


RegisterId(id)

Ensures that Ids subsequently generated by NewId do not clash with the given id.

Parameters:id (int) –


SafeShowMessage(title, text)

This function shows a message to the user in a safe way and should be safe to call even before the application has been initialized or if it is currently in some other strange state (for example, about to crash).

Under Windows this function shows a message box using a native dialog instead of MessageBox (which might be unsafe to call), elsewhere it simply prints the message to the standard output using the title as prefix.

Parameters:
  • title (string) – The title of the message box shown to the user or the prefix of the message string.
  • text (string) – The text to show to the user.

See also

LogFatalError



SafeYield(win=None, onlyIfNeeded=False)

Calls App.SafeYield .

Parameters:
  • win (Window) –
  • onlyIfNeeded (bool) –
Return type:

bool



SaveFileSelector(what, extension, default_name="", parent=None)

Ask for filename to save.

Parameters:
  • what (string) –
  • extension (string) –
  • default_name (string) –
  • parent (Window) –
Return type:

string



SetCursor(cursor)

Globally sets the cursor; only has an effect on Windows, Mac and GTK+.

You should call this function with NullCursor to restore the system cursor.

Parameters:cursor (Cursor) –


Shell(command="")

Executes a command in an interactive shell window.

If no command is specified, then just the shell is spawned.

Parameters:command (string) –
Return type:bool

See also

Execute,



Shutdown(flags=SHUTDOWN_POWEROFF)

This function shuts down or reboots the computer depending on the value of the flags.

Parameters:flags (int) – One of SHUTDOWN_POWEROFF , SHUTDOWN_REBOOT or SHUTDOWN_LOGOFF (currently implemented only for MSW) possibly combined with SHUTDOWN_FORCE which forces shutdown under MSW by forcefully terminating all the applications. As doing this can result in a data loss, this flag shouldn’t be used unless really necessary.
Return type:bool
Returns:True on success, False if an error occurred.

Note

Note that performing the shutdown requires the corresponding access rights (superuser under Unix, SE_SHUTDOWN privilege under Windows NT) and that this function is only implemented under Unix and MSW.



Sleep(secs)

Sleeps for the specified number of seconds.

Parameters:secs (int) –


StripMenuCodes(str, flags=Strip_All)

Strips any menu codes from str and returns the result.

By default, the functions strips both the mnemonics character ( '&' ) which is used to indicate a keyboard shortkey, and the accelerators, which are used only in the menu items and are separated from the main text by the \t (TAB) character. By using flags of Strip_Mnemonics or Strip_Accel to strip only the former or the latter part, respectively.

Notice that in most cases MenuItem.GetLabelFromText or Control.GetLabelText can be used instead.

Parameters:
  • str (string) –
  • flags (int) –
Return type:

string



SysErrorCode()

Returns the error code from the last system call.

This function uses errno on Unix platforms and GetLastError under Win32.

Return type:int


SysErrorMsg(errCode=0)

Returns the error message corresponding to the given system error code.

If errCode is 0 (default), the last error code (as returned by SysErrorCode) is used.

Parameters:errCode (long) –
Return type:string


Trap()

Generate a debugger exception meaning that the control is passed to the debugger if one is attached to the process.

Otherwise the program just terminates abnormally.

If DEBUG_LEVEL is 0 (which is not the default) this function does nothing.



Usleep(milliseconds)

Sleeps for the specified number of milliseconds.

Parameters:milliseconds (long) –

Deprecated since version 3.0.2: This function is deprecated because its name is misleading: notice that the argument is in milliseconds, not microseconds. Please use either MilliSleep or MicroSleep depending on the resolution you need.



version()

Returns a string containing version and port info



WakeUpIdle()

This function wakes up the (internal and platform dependent) idle system, i.e.

it will force the system to send an idle event even if the system currently is idle and thus would not send any idle event until after some other event would get sent. This is also useful for sending events between two threads and is used by the corresponding functions PostEvent and EvtHandler.AddPendingEvent .



Yield()

Calls AppConsole.Yield .

Return type:bool

Deprecated since version 3.0.2: This function is kept only for backwards compatibility. Please use the AppConsole.Yield method instead in any new code.