ImageTk.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # a Tk display interface
  6. #
  7. # History:
  8. # 96-04-08 fl Created
  9. # 96-09-06 fl Added getimage method
  10. # 96-11-01 fl Rewritten, removed image attribute and crop method
  11. # 97-05-09 fl Use PyImagingPaste method instead of image type
  12. # 97-05-12 fl Minor tweaks to match the IFUNC95 interface
  13. # 97-05-17 fl Support the "pilbitmap" booster patch
  14. # 97-06-05 fl Added file= and data= argument to image constructors
  15. # 98-03-09 fl Added width and height methods to Image classes
  16. # 98-07-02 fl Use default mode for "P" images without palette attribute
  17. # 98-07-02 fl Explicitly destroy Tkinter image objects
  18. # 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
  19. # 99-07-26 fl Automatically hook into Tkinter (if possible)
  20. # 99-08-15 fl Hook uses _imagingtk instead of _imaging
  21. #
  22. # Copyright (c) 1997-1999 by Secret Labs AB
  23. # Copyright (c) 1996-1997 by Fredrik Lundh
  24. #
  25. # See the README file for information on usage and redistribution.
  26. #
  27. from __future__ import annotations
  28. __lazy_modules__ = {"io", "tkinter"}
  29. import tkinter
  30. from io import BytesIO
  31. from . import Image, ImageFile
  32. TYPE_CHECKING = False
  33. if TYPE_CHECKING:
  34. from typing import Any
  35. from ._typing import CapsuleType
  36. # --------------------------------------------------------------------
  37. # Check for Tkinter interface hooks
  38. def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
  39. source = None
  40. if "file" in kw:
  41. source = kw.pop("file")
  42. elif "data" in kw:
  43. source = BytesIO(kw.pop("data"))
  44. if not source:
  45. return None
  46. return Image.open(source)
  47. def _pyimagingtkcall(
  48. command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType
  49. ) -> None:
  50. tk = photo.tk
  51. try:
  52. tk.call(command, photo, repr(ptr))
  53. except tkinter.TclError:
  54. # activate Tkinter hook
  55. # may raise an error if it cannot attach to Tkinter
  56. from . import _imagingtk
  57. _imagingtk.tkinit(tk.interpaddr())
  58. tk.call(command, photo, repr(ptr))
  59. # --------------------------------------------------------------------
  60. # PhotoImage
  61. class PhotoImage:
  62. """
  63. A Tkinter-compatible photo image. This can be used
  64. everywhere Tkinter expects an image object. If the image is an RGBA
  65. image, pixels having alpha 0 are treated as transparent.
  66. The constructor takes either a PIL image, or a mode and a size.
  67. Alternatively, you can use the ``file`` or ``data`` options to initialize
  68. the photo image object.
  69. :param image: Either a PIL image, or a mode string. If a mode string is
  70. used, a size must also be given.
  71. :param size: If the first argument is a mode string, this defines the size
  72. of the image.
  73. :keyword file: A filename to load the image from (using
  74. ``Image.open(file)``).
  75. :keyword data: An 8-bit string containing image data (as loaded from an
  76. image file).
  77. """
  78. def __init__(
  79. self,
  80. image: Image.Image | str | None = None,
  81. size: tuple[int, int] | None = None,
  82. **kw: Any,
  83. ) -> None:
  84. # Tk compatibility: file or data
  85. if image is None:
  86. image = _get_image_from_kw(kw)
  87. if image is None:
  88. msg = "Image is required"
  89. raise ValueError(msg)
  90. elif isinstance(image, str):
  91. mode = image
  92. image = None
  93. if size is None:
  94. msg = "If first argument is mode, size is required"
  95. raise ValueError(msg)
  96. else:
  97. # got an image instead of a mode
  98. mode = image.mode
  99. if mode == "P":
  100. # palette mapped data
  101. image.apply_transparency()
  102. image.load()
  103. mode = image.palette.mode if image.palette else "RGB"
  104. size = image.size
  105. kw["width"], kw["height"] = size
  106. if mode not in ["1", "L", "RGB", "RGBA"]:
  107. mode = Image.getmodebase(mode)
  108. self.__mode = mode
  109. self.__size = size
  110. self.__photo = tkinter.PhotoImage(**kw)
  111. self.tk = self.__photo.tk
  112. if image:
  113. self.paste(image)
  114. def __del__(self) -> None:
  115. try:
  116. name = self.__photo.name
  117. except AttributeError:
  118. return
  119. self.__photo.name = None
  120. try:
  121. self.__photo.tk.call("image", "delete", name)
  122. except Exception:
  123. pass # ignore internal errors
  124. def __str__(self) -> str:
  125. """
  126. Get the Tkinter photo image identifier. This method is automatically
  127. called by Tkinter whenever a PhotoImage object is passed to a Tkinter
  128. method.
  129. :return: A Tkinter photo image identifier (a string).
  130. """
  131. return str(self.__photo)
  132. def width(self) -> int:
  133. """
  134. Get the width of the image.
  135. :return: The width, in pixels.
  136. """
  137. return self.__size[0]
  138. def height(self) -> int:
  139. """
  140. Get the height of the image.
  141. :return: The height, in pixels.
  142. """
  143. return self.__size[1]
  144. def paste(self, im: Image.Image) -> None:
  145. """
  146. Paste a PIL image into the photo image. Note that this can
  147. be very slow if the photo image is displayed.
  148. :param im: A PIL image. The size must match the target region. If the
  149. mode does not match, the image is converted to the mode of
  150. the bitmap image.
  151. """
  152. # convert to blittable
  153. ptr = im.getim()
  154. image = im.im
  155. if not image.isblock() or im.mode != self.__mode:
  156. block = Image.core.new_block(self.__mode, im.size)
  157. image.convert_into(block) # convert directly between buffers
  158. ptr = block.ptr
  159. _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)
  160. # --------------------------------------------------------------------
  161. # BitmapImage
  162. class BitmapImage:
  163. """
  164. A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
  165. expects an image object.
  166. The given image must have mode "1". Pixels having value 0 are treated as
  167. transparent. Options, if any, are passed on to Tkinter. The most commonly
  168. used option is ``foreground``, which is used to specify the color for the
  169. non-transparent parts. See the Tkinter documentation for information on
  170. how to specify colours.
  171. :param image: A PIL image.
  172. """
  173. def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:
  174. # Tk compatibility: file or data
  175. if image is None:
  176. image = _get_image_from_kw(kw)
  177. if image is None:
  178. msg = "Image is required"
  179. raise ValueError(msg)
  180. self.__mode = image.mode
  181. self.__size = image.size
  182. self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)
  183. def __del__(self) -> None:
  184. try:
  185. name = self.__photo.name
  186. except AttributeError:
  187. return
  188. self.__photo.name = None
  189. try:
  190. self.__photo.tk.call("image", "delete", name)
  191. except Exception:
  192. pass # ignore internal errors
  193. def width(self) -> int:
  194. """
  195. Get the width of the image.
  196. :return: The width, in pixels.
  197. """
  198. return self.__size[0]
  199. def height(self) -> int:
  200. """
  201. Get the height of the image.
  202. :return: The height, in pixels.
  203. """
  204. return self.__size[1]
  205. def __str__(self) -> str:
  206. """
  207. Get the Tkinter bitmap image identifier. This method is automatically
  208. called by Tkinter whenever a BitmapImage object is passed to a Tkinter
  209. method.
  210. :return: A Tkinter bitmap image identifier (a string).
  211. """
  212. return str(self.__photo)
  213. def getimage(photo: PhotoImage) -> Image.Image:
  214. """Copies the contents of a PhotoImage to a PIL image memory."""
  215. im = Image.new("RGBA", (photo.width(), photo.height()))
  216. _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())
  217. return im