Python-Ref > GUI programming with PyGTK > Data structures > Clipboard
 
 

<-^^

Clipboard

How to work with clipboard.
GTK includes a Clipboard widget that lets the developer work with the system clipboard.
The Clipboard has many features, but we will concern ourselves only with the most basic manipulation of the clipboard.
Expand/Shrink
  1   # ensure that PyGTK 2.0 is loaded - not an older version
  2   import pygtk
  3   pygtk.require('2.0')
  4   # import the GTK module
  5   import gtk
  6   
  7   class MyGUI:
  8   
  9     def __init__( self, title):
 10       self.window = gtk.Window()
 11       self.title = title
 12       self.window.set_title( title)
 13       self.window.set_size_request( -1, -1)
 14       self.window.connect( "destroy", self.destroy)
 15       self.create_interior()
 16       self.window.show_all()
 17   
 18     def create_interior( self):
 19       self.mainbox = gtk.VBox()
 20       self.window.add( self.mainbox)
 21       # the label
 22       self.label = gtk.Label( "")
 23       self.mainbox.pack_start( self.label, padding=10)
 24       # the entry
 25       self.entry = gtk.Entry()
 26       self.mainbox.pack_start( self.entry, padding=10, expand=False)
 27       # buttons
 28       hbox = gtk.HButtonBox()
 29       b1 = gtk.Button( "Copy entry text")
 30       b1.connect( "clicked", self.copy_text)
 31       hbox.add( b1)
 32       b2 = gtk.Button( "Paste text to label")
 33       b2.connect( "clicked", self.set_text)
 34       hbox.add( b2)
 35       self.mainbox.pack_start( hbox, expand=False)
 36       # status bar
 37       self.status = gtk.Statusbar()
 38       self.mainbox.pack_end( self.status, expand=False)
 39       # show the box
 40       self.mainbox.show_all() 
 41   
 42     def set_text( self, w, data=None):
 43       clip = gtk.Clipboard()
 44       text = clip.wait_for_text() 
 45       cid = self.status.get_context_id( "app")
 46       if text:
 47         self.status.push( cid, "Setting label text to '%s'" % text)
 48         self.label.set_label( text)
 49       else:
 50         self.status.push( cid, "The clipboard is empty!")
 51   
 52     def copy_text( self, w):
 53       clip = gtk.Clipboard()
 54       text = self.entry.get_text()
 55       clip.set_text( text)
 56       cid = self.status.get_context_id( "app")
 57       self.status.push( cid, "Text '%s' was copied to clipboard" % text)
 58   
 59     def main( self):
 60       gtk.main()
 61   
 62     def destroy( self, w):
 63       gtk.main_quit()
 64   
 65   
 66   if __name__ == "__main__":
 67     m = MyGUI( "Clipboard example")
 68     m.main()
Screenshot:
Program screenshot gtk-clipboard1-1.pngProgram screenshot gtk-clipboard1-1a.pngProgram screenshot gtk-clipboard1-1b.png
Doba běhu: 1607.8 ms