The clipboard is a system resource used to pass user data between applications in the operating system. This is most often associated with copying and pasting actions in an application. This recipe will show some basics on putting and getting data from the clipboard.
Let's first define a helper function to get some text from the clipboard, as follows:
def GetClipboardText(): text_obj = wx.TextDataObject() rtext = "" if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): if wx.TheClipboard.GetData(text_obj): rtext = text_obj.GetText() wx.TheClipboard.Close() return rtext
Now, let's do the reverse and define a helper function to put text into the clipboard, as done with the following code:
def SetClipboardText(text): data_o = wx.TextDataObject() data_o.SetText(text) if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): wx.TheClipboard.SetData(data_o) wx.TheClipboard.Close()
Both functions work by creating TextDataObject
, which provides a platform-independent way to represent the systems' native data format. Then, TheClipboard
object is opened, and it is used to either get data from the clipboard of the given type or put data in the clipboard from the application. This can be boiled down to a simple three step process for any clipboard interaction:
Open clipboard
Set or get
DataObject
Close the clipboard
Closing the clipboard after using is very important; it may prevent other processes from accessing it. The clipboard should only be kept open momentarily.