The clipboard in action

In this section, we'll display a simple example that illustrates how to pass data to and from the clipboard. It's a frame with two buttons that allows the user to copy and paste text. When you run it, the example should look like figure 18.1. Listing 18.1 displays the code used to produce figure 18.1.

□ Clipboard _BOHDB

The whole contents of this control will be placed in the system's clipboard when you click the copy button below.

If the clipboard contains a text data object then it will be placed in this control when you click the paste button below. Try copying to and pasting from other applications too!

AJ A)

±i JJ

Copy

Paste

Figure 18.1 An example frame that uses the clipboard

Listing 18.1 A sample clipboard transaction import wx t1_text = \

The whole contents of this control will be placed in the system's clipboard when you click the copy button below.

If the clipboard contains a text data object then it will be placed in this control when you click the paste button below. Try copying to and pasting from other applications too!

class MyFrame(wx.Frame):

wx.Frame._init_(self, None, title="Clipboard", size=(500,3 00))

self.t1 = wx.TextCtrl(p, -1, t1_text, style=wx.TE_MULTILINE|wx.HSCROLL) self.t2 = wx.TextCtrl(p, -1, t2_text, style=wx.TE_MULTILINE|wx.HSCROLL) copy = wx.Button(p, -1, "Copy") paste = wx.Button(p, -1, "Paste")

fgs.AddGrowableRow(0)

fgs.AddGrowableCol(0)

fgs.AddGrowableCol(1) fgs.Add(self.t1, 0, wx.EXPAND) fgs.Add(self.t2, 0, wx.EXPAND) fgs.Add(copy, 0, wx.EXPAND) fgs.Add(paste, 0, wx.EXPAND) border = wx.BoxSizer()

border.Add(fgs, 1, wx.EXPAND|wx.ALL, 5) p.SetSizer(border)

self.Bind(wx.EVT_BUTTON, self.OnDoCopy, copy) self.Bind(wx.EVT_BUTTON, self.OnDoPaste, paste)

def OnDoCopy(self, evt): «-1 Copy button event handler data = wx.TextDataObject() data.SetText(self.t1.GetValue()) if wx.TheClipboard.Open():

wx.TheClipboard.SetData(data) wx.TheClipboard.Close() else:

wx.MessageBox("Unable to open the clipboard", "Error")

Placing data on clipboard def OnDoPaste(self, evt): <— Paste button event handler success = False data = wx.TextDataObject()

if wx.TheClipboard.Open():

success = wx.TheClipboard.GetData(data) <1— wx.TheClipboard.Close()

Getting data from clipboard if success:

self.t2.SetValue(data.GetText()) else:

wx.MessageBox(

"There is no data in the clipboard in the required format", "Error")

Updating the text widget app = wx.PySimpleApp() frm = MyFrame() frm.Show() app.MainLoop()

In the next section, we'll discuss how to pass other data formats such as bitmaps.

Was this article helpful?

0 0

Post a comment