If you want your application to be a source for a clipboard event, meaning you want to be able to cut or copy data to the clipboard, place that data inside a wx.DataObject wrapper. The wx.DataObject wrapper class allows you to have metadata, meaning that the object also knows what kind of formats it can be read from or written as. This would be important if, for example, you were writing a word processing program and wanted to give the user the option of pasting in data as unformatted text or as formatted rich text. Most of the time, however, you don't need that much power or flexibility in your clipboard activity. wxPython provides three predefined subclasses of wx.DataObject for the most common use cases: plain text, bitmap image, and a filename. All of these derived objects are subclasses of wx.DataObject via the concrete subclass wx.DataObjectSimple. The data object simple class is specifically meant to be the parent class for data objects that have exactly one format.
To pass plain text, create an instance of the class wx.TextDataObject, using its constructor:
The text parameter is the text that you want to pass to the clipboard. If you don't know the text when you create the object, you can set the text with the Set-Text(text) method. You can recover the text using the GetText() method, and you can also find out how long the text is with the method GetTextLength().
Having created the data object, you must then access the clipboard. The system clipboard is a global object in wxPython, named wx.TheClipboard. To use the clipboard, open it using the clipboard method Open(). The method returns a Boolean True if the clipboard has been opened, and False otherwise. It is possible for the clipboard open to fail if the clipboard is being written to by another application, so you should check the return value before using the clipboard. When you are done using the clipboard, close it by calling the clipboard method Close(). Leaving the clipboard open can block other clipboard users, so the goal is to have it open for as small an amount of time as possible.
Was this article helpful?