class main ( ):
def __init__(self, parent):
#super ( ).__init__()
self.menu = tk.Menu ( parent, tearoff = 0,
postcommand = self.enable_selection )
self.menu.add_command ( label = 'Cut', command = self.cut_text )
self.menu.add_command ( label = 'Copy', command = self.copy_text )
self.menu.add_command ( label = 'Paste', command = self.paste_text )
self.menu.add_command ( label = 'Delete', command = self.delete_text )
self.text = tk.Text ( height = 10, width = 50 )
self.text.bind ( '<Button-3>', self.show_popup )
self.text.pack ()
mainloop ()
def enable_selection ( self ):
self.state_clipboard = tk.ACTIVE
if self.text.tag_ranges (tk.SEL):
self.state_selection = tk.ACTIVE
else:
self.state_selection = tk.DISABLED
try:
self.text.selection_get ()
except tk.TclError as e:
pass
#print ( e )
#self.state_clipboard = tk.DISABLED
#self.menu.entryconfig ( 0, state = self.state_selection )
#self.menu.entryconfig ( 1, state = self.state_selection )
#self.menu.entryconfig ( 2, state = self.state_clipboard )
#self.menu.entryconfig ( 3, state = self.state_selection )
def cut_text ( self ):
self.copy_text ()
self.delete_text ()
def copy_text ( self ):
selection = self.text.tag_ranges ( tk.SEL )
if selection:
self.text.clipboard_clear ()
self.text.clipboard_append ( self.text.get (*selection) )
def paste_text ( self ):
try:
self.text.insert ( tk.INSERT, self.text.clipboard_get () )
except tk.TclError:
pass
def delete_text ( self ):
selection = self.text.tag_ranges ( tk.SEL )
if selection:
self.text.delete ( *selection )
def show_popup ( self, event ):
self.menu.post ( event.x_root, event.y_root )
if __name__ == '__main__':
app = main ( tk.Tk() )