TLSK
TLSK

Reputation: 273

In wxpython copy, cut, paste, and select all text from one TextCtrl to an other

I want to cut, paste, copy, and select the text from textcrtl to textcrtl. Can anyone help me please, my mind has stack for hours. Look the code below, thanks for your help...

import wx
import os

class Editor(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600, 500))

        # setting up menubar
        menubar = wx.MenuBar()

        edit = wx.Menu()
        cut = wx.MenuItem(edit, 106, '&Cut\tCtrl+X', 'Cut the Selection')
        edit.AppendItem(cut)

        copy = wx.MenuItem(edit, 107, '&Copy\tCtrl+C', 'Copy the Selection')
        edit.AppendItem(copy)

        paste = wx.MenuItem(edit, 108, '&Paste\tCtrl+V', 'Paste text from clipboard')
        edit.AppendItem(paste)

        delete = wx.MenuItem(edit, 109, '&Delete', 'Delete the selected text')
        edit.AppendItem(delete)

        edit.Append(110, 'Select &All\tCtrl+A', 'Select the entire text')

        menubar.Append(edit, '&Edit')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.OnCut, id=106)
        self.Bind(wx.EVT_MENU, self.OnCopy, id=107)
        self.Bind(wx.EVT_MENU, self.OnPaste, id=108)
        self.Bind(wx.EVT_MENU, self.OnDelete, id=109)
        self.Bind(wx.EVT_MENU, self.OnSelectAll, id=110)

        self.text = wx.TextCtrl(self, -1, '', (110,55),(120, -1))
        self.text = wx.TextCtrl(self, -1, '', (110,95),(120, -1))
        self.text.SetFocus()

        self.Centre()
        self.Show(True)

    def OnCut(self, event):
         self.text.Cut()

    def OnCopy(self, event):
         self.text.Copy()

    def OnPaste(self, event):
        self.text.Paste()

    def OnDelete(self, event):
        frm, to = self.text.GetSelection()
        self.text.Remove(frm, to)

    def OnSelectAll(self, event):
       self.text.SelectAll()


app = wx.App()
Editor(None, -1, 'Editor')
app.MainLoop() 

Upvotes: 1

Views: 3024

Answers (1)

Andrey Sobolev
Andrey Sobolev

Reputation: 12713

You need to know the wx.TextCtrl instance from which to cut, copy or where to paste text. In the code snippet you provided, you tried to do it with self.text, but as Velociraptors has already said, you initialized self.text twice, so you lost the access to the first wx.TextCtrl by name. Therefore, first you have to get wx.TextCtrl instance you are working with, and then use its methods. This could be done with wx.Frame.FindFocus() class, which returns the widget in a frame which has the focus (or None).

So, for Cut we get something like this:

def OnCut(self, event):
    text = self.FindFocus()
    if text is not None:
        text.Cut()

Other methods can be modified the same way.

Upvotes: 2

Related Questions