scrap_clipboard.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/env python
  2. """
  3. Demonstrates the clipboard capabilities of pygame.
  4. """
  5. import os
  6. import pygame
  7. from pygame.locals import *
  8. import pygame.scrap as scrap
  9. from pygame.compat import as_bytes
  10. BytesIO = pygame.compat.get_BytesIO()
  11. def usage ():
  12. print ("Press the 'g' key to get all of the current clipboard data")
  13. print ("Press the 'p' key to put a string into the clipboard")
  14. print ("Press the 'a' key to get a list of the currently available types")
  15. print ("Press the 'i' key to put an image into the clipboard")
  16. main_dir = os.path.split(os.path.abspath(__file__))[0]
  17. pygame.init ()
  18. screen = pygame.display.set_mode ((200, 200))
  19. c = pygame.time.Clock ()
  20. going = True
  21. # Initialize the scrap module and use the clipboard mode.
  22. scrap.init ()
  23. scrap.set_mode (SCRAP_CLIPBOARD)
  24. usage ()
  25. while going:
  26. for e in pygame.event.get ():
  27. if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
  28. going = False
  29. elif e.type == KEYDOWN and e.key == K_g:
  30. # This means to look for data.
  31. print ("Getting the different clipboard data..")
  32. for t in scrap.get_types ():
  33. r = scrap.get (t)
  34. if r and len (r) > 500:
  35. print ("Type %s : (large %i byte buffer)" % (t, len(r)))
  36. elif r is None:
  37. print ("Type %s : None" % (t,))
  38. else:
  39. print ("Type %s : '%s'" % (t, r.decode('ascii', 'ignore')))
  40. if "image" in t:
  41. namehint = t.split("/")[1]
  42. if namehint in ['bmp', 'png', 'jpg']:
  43. f = BytesIO(r)
  44. loaded_surf = pygame.image.load(f, "." + namehint)
  45. screen.blit(loaded_surf, (0,0))
  46. elif e.type == KEYDOWN and e.key == K_p:
  47. # Place some text into the selection.
  48. print ("Placing clipboard text.")
  49. scrap.put (SCRAP_TEXT,
  50. as_bytes("Hello. This is a message from scrap."))
  51. elif e.type == KEYDOWN and e.key == K_a:
  52. # Get all available types.
  53. print ("Getting the available types from the clipboard.")
  54. types = scrap.get_types ()
  55. print (types)
  56. if len (types) > 0:
  57. print ("Contains %s: %s" %
  58. (types[0], scrap.contains (types[0])))
  59. print ("Contains _INVALID_: ", scrap.contains ("_INVALID_"))
  60. elif e.type == KEYDOWN and e.key == K_i:
  61. print ("Putting image into the clipboard.")
  62. scrap.set_mode (SCRAP_CLIPBOARD)
  63. fp = open (os.path.join(main_dir, 'data', 'liquid.bmp'), 'rb')
  64. buf = fp.read ()
  65. scrap.put ("image/bmp", buf)
  66. fp.close ()
  67. elif e.type in (KEYDOWN, MOUSEBUTTONDOWN):
  68. usage ()
  69. pygame.display.flip()
  70. c.tick(40)