We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
"box" parameter of PIL.ImageTk.PhotoImage.paste method appears to be dysfunctional
The "**box**" 4-tuple parameter of the **PIL.ImageTk.PhotoImage.paste** method is intended to allow a PIL Image to be pasted onto a Tkinter compatible PhotoImage within the specified box coordinates, but "box" appears to be dysfunctional, and I can't see anything in the source code of the method to implement its function. Smaller images pasted to larger images appear top-left and ignore any "box" value.

The documentation detailing the "box" parameter is here:
https://pillow.readthedocs.io/en/stable/reference/ImageTk.html#PIL.ImageTk.PhotoImage.paste

The source code of the paste method includes "box" as a parameter and has a docstring for it:
https://github.com/python-pillow/Pillow/blob/main/src/PIL/ImageTk.py#L178

Test code. A smaller blue box pasted into a larger yellow box always appears top-left and ignores the paste coordinates:

```python
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
pil_img1 = Image.new("RGB",(400, 200), "yellow")
tk_img1 = ImageTk.PhotoImage(pil_img1)
tk.Label(root, image=tk_img1).pack()
pil_img2 = Image.new("RGB",(200, 100), "blue")
tk_img1.paste(pil_img2, box=(100, 50, 200, 150))
root.mainloop()
```

Tested with    Windows 10,   Python 3.10.4, Pillow 9.0.1
and with       Ubuntu 21.10, Python 3.9.7,  Pillow 8.1.2


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/PIL/ImageTk.py`
Content:
```
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 
28 import tkinter
29 from io import BytesIO
30 
31 from . import Image
32 
33 # --------------------------------------------------------------------
34 # Check for Tkinter interface hooks
35 
36 _pilbitmap_ok = None
37 
38 
39 def _pilbitmap_check():
40     global _pilbitmap_ok
41     if _pilbitmap_ok is None:
42         try:
43             im = Image.new("1", (1, 1))
44             tkinter.BitmapImage(data=f"PIL:{im.im.id}")
45             _pilbitmap_ok = 1
46         except tkinter.TclError:
47             _pilbitmap_ok = 0
48     return _pilbitmap_ok
49 
50 
51 def _get_image_from_kw(kw):
52     source = None
53     if "file" in kw:
54         source = kw.pop("file")
55     elif "data" in kw:
56         source = BytesIO(kw.pop("data"))
57     if source:
58         return Image.open(source)
59 
60 
61 def _pyimagingtkcall(command, photo, id):
62     tk = photo.tk
63     try:
64         tk.call(command, photo, id)
65     except tkinter.TclError:
66         # activate Tkinter hook
67         # may raise an error if it cannot attach to Tkinter
68         from . import _imagingtk
69 
70         try:
71             if hasattr(tk, "interp"):
72                 # Required for PyPy, which always has CFFI installed
73                 from cffi import FFI
74 
75                 ffi = FFI()
76 
77                 # PyPy is using an FFI CDATA element
78                 # (Pdb) self.tk.interp
79                 #  <cdata 'Tcl_Interp *' 0x3061b50>
80                 _imagingtk.tkinit(int(ffi.cast("uintptr_t", tk.interp)), 1)
81             else:
82                 _imagingtk.tkinit(tk.interpaddr(), 1)
83         except AttributeError:
84             _imagingtk.tkinit(id(tk), 0)
85         tk.call(command, photo, id)
86 
87 
88 # --------------------------------------------------------------------
89 # PhotoImage
90 
91 
92 class PhotoImage:
93     """
94     A Tkinter-compatible photo image.  This can be used
95     everywhere Tkinter expects an image object.  If the image is an RGBA
96     image, pixels having alpha 0 are treated as transparent.
97 
98     The constructor takes either a PIL image, or a mode and a size.
99     Alternatively, you can use the ``file`` or ``data`` options to initialize
100     the photo image object.
101 
102     :param image: Either a PIL image, or a mode string.  If a mode string is
103                   used, a size must also be given.
104     :param size: If the first argument is a mode string, this defines the size
105                  of the image.
106     :keyword file: A filename to load the image from (using
107                    ``Image.open(file)``).
108     :keyword data: An 8-bit string containing image data (as loaded from an
109                    image file).
110     """
111 
112     def __init__(self, image=None, size=None, **kw):
113 
114         # Tk compatibility: file or data
115         if image is None:
116             image = _get_image_from_kw(kw)
117 
118         if hasattr(image, "mode") and hasattr(image, "size"):
119             # got an image instead of a mode
120             mode = image.mode
121             if mode == "P":
122                 # palette mapped data
123                 image.load()
124                 try:
125                     mode = image.palette.mode
126                 except AttributeError:
127                     mode = "RGB"  # default
128             size = image.size
129             kw["width"], kw["height"] = size
130         else:
131             mode = image
132             image = None
133 
134         if mode not in ["1", "L", "RGB", "RGBA"]:
135             mode = Image.getmodebase(mode)
136 
137         self.__mode = mode
138         self.__size = size
139         self.__photo = tkinter.PhotoImage(**kw)
140         self.tk = self.__photo.tk
141         if image:
142             self.paste(image)
143 
144     def __del__(self):
145         name = self.__photo.name
146         self.__photo.name = None
147         try:
148             self.__photo.tk.call("image", "delete", name)
149         except Exception:
150             pass  # ignore internal errors
151 
152     def __str__(self):
153         """
154         Get the Tkinter photo image identifier.  This method is automatically
155         called by Tkinter whenever a PhotoImage object is passed to a Tkinter
156         method.
157 
158         :return: A Tkinter photo image identifier (a string).
159         """
160         return str(self.__photo)
161 
162     def width(self):
163         """
164         Get the width of the image.
165 
166         :return: The width, in pixels.
167         """
168         return self.__size[0]
169 
170     def height(self):
171         """
172         Get the height of the image.
173 
174         :return: The height, in pixels.
175         """
176         return self.__size[1]
177 
178     def paste(self, im, box=None):
179         """
180         Paste a PIL image into the photo image.  Note that this can
181         be very slow if the photo image is displayed.
182 
183         :param im: A PIL image. The size must match the target region.  If the
184                    mode does not match, the image is converted to the mode of
185                    the bitmap image.
186         :param box: A 4-tuple defining the left, upper, right, and lower pixel
187                     coordinate. See :ref:`coordinate-system`. If None is given
188                     instead of a tuple, all of the image is assumed.
189         """
190 
191         # convert to blittable
192         im.load()
193         image = im.im
194         if image.isblock() and im.mode == self.__mode:
195             block = image
196         else:
197             block = image.new_block(self.__mode, im.size)
198             image.convert2(block, image)  # convert directly between buffers
199 
200         _pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
201 
202 
203 # --------------------------------------------------------------------
204 # BitmapImage
205 
206 
207 class BitmapImage:
208     """
209     A Tkinter-compatible bitmap image.  This can be used everywhere Tkinter
210     expects an image object.
211 
212     The given image must have mode "1".  Pixels having value 0 are treated as
213     transparent.  Options, if any, are passed on to Tkinter.  The most commonly
214     used option is ``foreground``, which is used to specify the color for the
215     non-transparent parts.  See the Tkinter documentation for information on
216     how to specify colours.
217 
218     :param image: A PIL image.
219     """
220 
221     def __init__(self, image=None, **kw):
222 
223         # Tk compatibility: file or data
224         if image is None:
225             image = _get_image_from_kw(kw)
226 
227         self.__mode = image.mode
228         self.__size = image.size
229 
230         if _pilbitmap_check():
231             # fast way (requires the pilbitmap booster patch)
232             image.load()
233             kw["data"] = f"PIL:{image.im.id}"
234             self.__im = image  # must keep a reference
235         else:
236             # slow but safe way
237             kw["data"] = image.tobitmap()
238         self.__photo = tkinter.BitmapImage(**kw)
239 
240     def __del__(self):
241         name = self.__photo.name
242         self.__photo.name = None
243         try:
244             self.__photo.tk.call("image", "delete", name)
245         except Exception:
246             pass  # ignore internal errors
247 
248     def width(self):
249         """
250         Get the width of the image.
251 
252         :return: The width, in pixels.
253         """
254         return self.__size[0]
255 
256     def height(self):
257         """
258         Get the height of the image.
259 
260         :return: The height, in pixels.
261         """
262         return self.__size[1]
263 
264     def __str__(self):
265         """
266         Get the Tkinter bitmap image identifier.  This method is automatically
267         called by Tkinter whenever a BitmapImage object is passed to a Tkinter
268         method.
269 
270         :return: A Tkinter bitmap image identifier (a string).
271         """
272         return str(self.__photo)
273 
274 
275 def getimage(photo):
276     """Copies the contents of a PhotoImage to a PIL image memory."""
277     im = Image.new("RGBA", (photo.width(), photo.height()))
278     block = im.im
279 
280     _pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
281 
282     return im
283 
284 
285 def _show(image, title):
286     """Helper for the Image.show method."""
287 
288     class UI(tkinter.Label):
289         def __init__(self, master, im):
290             if im.mode == "1":
291                 self.image = BitmapImage(im, foreground="white", master=master)
292             else:
293                 self.image = PhotoImage(im, master=master)
294             super().__init__(master, image=self.image, bg="black", bd=0)
295 
296     if not tkinter._default_root:
297         raise OSError("tkinter not initialized")
298     top = tkinter.Toplevel()
299     if title:
300         top.title(title)
301     UI(top, image).pack()
302
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/PIL/ImageTk.py b/src/PIL/ImageTk.py
--- a/src/PIL/ImageTk.py
+++ b/src/PIL/ImageTk.py
@@ -26,6 +26,7 @@
 #
 
 import tkinter
+import warnings
 from io import BytesIO
 
 from . import Image
@@ -183,11 +184,15 @@
         :param im: A PIL image. The size must match the target region.  If the
                    mode does not match, the image is converted to the mode of
                    the bitmap image.
-        :param box: A 4-tuple defining the left, upper, right, and lower pixel
-                    coordinate. See :ref:`coordinate-system`. If None is given
-                    instead of a tuple, all of the image is assumed.
         """
 
+        if box is not None:
+            warnings.warn(
+                "The box parameter is deprecated and will be removed in Pillow 10 "
+                "(2023-07-01).",
+                DeprecationWarning,
+            )
+
         # convert to blittable
         im.load()
         image = im.im

{"golden_diff": "diff --git a/src/PIL/ImageTk.py b/src/PIL/ImageTk.py\n--- a/src/PIL/ImageTk.py\n+++ b/src/PIL/ImageTk.py\n@@ -26,6 +26,7 @@\n #\n \n import tkinter\n+import warnings\n from io import BytesIO\n \n from . import Image\n@@ -183,11 +184,15 @@\n         :param im: A PIL image. The size must match the target region.  If the\n                    mode does not match, the image is converted to the mode of\n                    the bitmap image.\n-        :param box: A 4-tuple defining the left, upper, right, and lower pixel\n-                    coordinate. See :ref:`coordinate-system`. If None is given\n-                    instead of a tuple, all of the image is assumed.\n         \"\"\"\n \n+        if box is not None:\n+            warnings.warn(\n+                \"The box parameter is deprecated and will be removed in Pillow 10 \"\n+                \"(2023-07-01).\",\n+                DeprecationWarning,\n+            )\n+\n         # convert to blittable\n         im.load()\n         image = im.im\n", "issue": "\"box\" parameter of PIL.ImageTk.PhotoImage.paste method appears to be dysfunctional\nThe \"**box**\" 4-tuple parameter of the **PIL.ImageTk.PhotoImage.paste** method is intended to allow a PIL Image to be pasted onto a Tkinter compatible PhotoImage within the specified box coordinates, but \"box\" appears to be dysfunctional, and I can't see anything in the source code of the method to implement its function. Smaller images pasted to larger images appear top-left and ignore any \"box\" value.\r\n\r\nThe documentation detailing the \"box\" parameter is here:\r\nhttps://pillow.readthedocs.io/en/stable/reference/ImageTk.html#PIL.ImageTk.PhotoImage.paste\r\n\r\nThe source code of the paste method includes \"box\" as a parameter and has a docstring for it:\r\nhttps://github.com/python-pillow/Pillow/blob/main/src/PIL/ImageTk.py#L178\r\n\r\nTest code. A smaller blue box pasted into a larger yellow box always appears top-left and ignores the paste coordinates:\r\n\r\n```python\r\nimport tkinter as tk\r\nfrom PIL import Image, ImageTk\r\nroot = tk.Tk()\r\npil_img1 = Image.new(\"RGB\",(400, 200), \"yellow\")\r\ntk_img1 = ImageTk.PhotoImage(pil_img1)\r\ntk.Label(root, image=tk_img1).pack()\r\npil_img2 = Image.new(\"RGB\",(200, 100), \"blue\")\r\ntk_img1.paste(pil_img2, box=(100, 50, 200, 150))\r\nroot.mainloop()\r\n```\r\n\r\nTested with    Windows 10,   Python 3.10.4, Pillow 9.0.1\r\nand with       Ubuntu 21.10, Python 3.9.7,  Pillow 8.1.2\r\n\n", "before_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# a Tk display interface\n#\n# History:\n# 96-04-08 fl   Created\n# 96-09-06 fl   Added getimage method\n# 96-11-01 fl   Rewritten, removed image attribute and crop method\n# 97-05-09 fl   Use PyImagingPaste method instead of image type\n# 97-05-12 fl   Minor tweaks to match the IFUNC95 interface\n# 97-05-17 fl   Support the \"pilbitmap\" booster patch\n# 97-06-05 fl   Added file= and data= argument to image constructors\n# 98-03-09 fl   Added width and height methods to Image classes\n# 98-07-02 fl   Use default mode for \"P\" images without palette attribute\n# 98-07-02 fl   Explicitly destroy Tkinter image objects\n# 99-07-24 fl   Support multiple Tk interpreters (from Greg Couch)\n# 99-07-26 fl   Automatically hook into Tkinter (if possible)\n# 99-08-15 fl   Hook uses _imagingtk instead of _imaging\n#\n# Copyright (c) 1997-1999 by Secret Labs AB\n# Copyright (c) 1996-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport tkinter\nfrom io import BytesIO\n\nfrom . import Image\n\n# --------------------------------------------------------------------\n# Check for Tkinter interface hooks\n\n_pilbitmap_ok = None\n\n\ndef _pilbitmap_check():\n    global _pilbitmap_ok\n    if _pilbitmap_ok is None:\n        try:\n            im = Image.new(\"1\", (1, 1))\n            tkinter.BitmapImage(data=f\"PIL:{im.im.id}\")\n            _pilbitmap_ok = 1\n        except tkinter.TclError:\n            _pilbitmap_ok = 0\n    return _pilbitmap_ok\n\n\ndef _get_image_from_kw(kw):\n    source = None\n    if \"file\" in kw:\n        source = kw.pop(\"file\")\n    elif \"data\" in kw:\n        source = BytesIO(kw.pop(\"data\"))\n    if source:\n        return Image.open(source)\n\n\ndef _pyimagingtkcall(command, photo, id):\n    tk = photo.tk\n    try:\n        tk.call(command, photo, id)\n    except tkinter.TclError:\n        # activate Tkinter hook\n        # may raise an error if it cannot attach to Tkinter\n        from . import _imagingtk\n\n        try:\n            if hasattr(tk, \"interp\"):\n                # Required for PyPy, which always has CFFI installed\n                from cffi import FFI\n\n                ffi = FFI()\n\n                # PyPy is using an FFI CDATA element\n                # (Pdb) self.tk.interp\n                #  <cdata 'Tcl_Interp *' 0x3061b50>\n                _imagingtk.tkinit(int(ffi.cast(\"uintptr_t\", tk.interp)), 1)\n            else:\n                _imagingtk.tkinit(tk.interpaddr(), 1)\n        except AttributeError:\n            _imagingtk.tkinit(id(tk), 0)\n        tk.call(command, photo, id)\n\n\n# --------------------------------------------------------------------\n# PhotoImage\n\n\nclass PhotoImage:\n    \"\"\"\n    A Tkinter-compatible photo image.  This can be used\n    everywhere Tkinter expects an image object.  If the image is an RGBA\n    image, pixels having alpha 0 are treated as transparent.\n\n    The constructor takes either a PIL image, or a mode and a size.\n    Alternatively, you can use the ``file`` or ``data`` options to initialize\n    the photo image object.\n\n    :param image: Either a PIL image, or a mode string.  If a mode string is\n                  used, a size must also be given.\n    :param size: If the first argument is a mode string, this defines the size\n                 of the image.\n    :keyword file: A filename to load the image from (using\n                   ``Image.open(file)``).\n    :keyword data: An 8-bit string containing image data (as loaded from an\n                   image file).\n    \"\"\"\n\n    def __init__(self, image=None, size=None, **kw):\n\n        # Tk compatibility: file or data\n        if image is None:\n            image = _get_image_from_kw(kw)\n\n        if hasattr(image, \"mode\") and hasattr(image, \"size\"):\n            # got an image instead of a mode\n            mode = image.mode\n            if mode == \"P\":\n                # palette mapped data\n                image.load()\n                try:\n                    mode = image.palette.mode\n                except AttributeError:\n                    mode = \"RGB\"  # default\n            size = image.size\n            kw[\"width\"], kw[\"height\"] = size\n        else:\n            mode = image\n            image = None\n\n        if mode not in [\"1\", \"L\", \"RGB\", \"RGBA\"]:\n            mode = Image.getmodebase(mode)\n\n        self.__mode = mode\n        self.__size = size\n        self.__photo = tkinter.PhotoImage(**kw)\n        self.tk = self.__photo.tk\n        if image:\n            self.paste(image)\n\n    def __del__(self):\n        name = self.__photo.name\n        self.__photo.name = None\n        try:\n            self.__photo.tk.call(\"image\", \"delete\", name)\n        except Exception:\n            pass  # ignore internal errors\n\n    def __str__(self):\n        \"\"\"\n        Get the Tkinter photo image identifier.  This method is automatically\n        called by Tkinter whenever a PhotoImage object is passed to a Tkinter\n        method.\n\n        :return: A Tkinter photo image identifier (a string).\n        \"\"\"\n        return str(self.__photo)\n\n    def width(self):\n        \"\"\"\n        Get the width of the image.\n\n        :return: The width, in pixels.\n        \"\"\"\n        return self.__size[0]\n\n    def height(self):\n        \"\"\"\n        Get the height of the image.\n\n        :return: The height, in pixels.\n        \"\"\"\n        return self.__size[1]\n\n    def paste(self, im, box=None):\n        \"\"\"\n        Paste a PIL image into the photo image.  Note that this can\n        be very slow if the photo image is displayed.\n\n        :param im: A PIL image. The size must match the target region.  If the\n                   mode does not match, the image is converted to the mode of\n                   the bitmap image.\n        :param box: A 4-tuple defining the left, upper, right, and lower pixel\n                    coordinate. See :ref:`coordinate-system`. If None is given\n                    instead of a tuple, all of the image is assumed.\n        \"\"\"\n\n        # convert to blittable\n        im.load()\n        image = im.im\n        if image.isblock() and im.mode == self.__mode:\n            block = image\n        else:\n            block = image.new_block(self.__mode, im.size)\n            image.convert2(block, image)  # convert directly between buffers\n\n        _pyimagingtkcall(\"PyImagingPhoto\", self.__photo, block.id)\n\n\n# --------------------------------------------------------------------\n# BitmapImage\n\n\nclass BitmapImage:\n    \"\"\"\n    A Tkinter-compatible bitmap image.  This can be used everywhere Tkinter\n    expects an image object.\n\n    The given image must have mode \"1\".  Pixels having value 0 are treated as\n    transparent.  Options, if any, are passed on to Tkinter.  The most commonly\n    used option is ``foreground``, which is used to specify the color for the\n    non-transparent parts.  See the Tkinter documentation for information on\n    how to specify colours.\n\n    :param image: A PIL image.\n    \"\"\"\n\n    def __init__(self, image=None, **kw):\n\n        # Tk compatibility: file or data\n        if image is None:\n            image = _get_image_from_kw(kw)\n\n        self.__mode = image.mode\n        self.__size = image.size\n\n        if _pilbitmap_check():\n            # fast way (requires the pilbitmap booster patch)\n            image.load()\n            kw[\"data\"] = f\"PIL:{image.im.id}\"\n            self.__im = image  # must keep a reference\n        else:\n            # slow but safe way\n            kw[\"data\"] = image.tobitmap()\n        self.__photo = tkinter.BitmapImage(**kw)\n\n    def __del__(self):\n        name = self.__photo.name\n        self.__photo.name = None\n        try:\n            self.__photo.tk.call(\"image\", \"delete\", name)\n        except Exception:\n            pass  # ignore internal errors\n\n    def width(self):\n        \"\"\"\n        Get the width of the image.\n\n        :return: The width, in pixels.\n        \"\"\"\n        return self.__size[0]\n\n    def height(self):\n        \"\"\"\n        Get the height of the image.\n\n        :return: The height, in pixels.\n        \"\"\"\n        return self.__size[1]\n\n    def __str__(self):\n        \"\"\"\n        Get the Tkinter bitmap image identifier.  This method is automatically\n        called by Tkinter whenever a BitmapImage object is passed to a Tkinter\n        method.\n\n        :return: A Tkinter bitmap image identifier (a string).\n        \"\"\"\n        return str(self.__photo)\n\n\ndef getimage(photo):\n    \"\"\"Copies the contents of a PhotoImage to a PIL image memory.\"\"\"\n    im = Image.new(\"RGBA\", (photo.width(), photo.height()))\n    block = im.im\n\n    _pyimagingtkcall(\"PyImagingPhotoGet\", photo, block.id)\n\n    return im\n\n\ndef _show(image, title):\n    \"\"\"Helper for the Image.show method.\"\"\"\n\n    class UI(tkinter.Label):\n        def __init__(self, master, im):\n            if im.mode == \"1\":\n                self.image = BitmapImage(im, foreground=\"white\", master=master)\n            else:\n                self.image = PhotoImage(im, master=master)\n            super().__init__(master, image=self.image, bg=\"black\", bd=0)\n\n    if not tkinter._default_root:\n        raise OSError(\"tkinter not initialized\")\n    top = tkinter.Toplevel()\n    if title:\n        top.title(title)\n    UI(top, image).pack()\n", "path": "src/PIL/ImageTk.py"}], "after_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# a Tk display interface\n#\n# History:\n# 96-04-08 fl   Created\n# 96-09-06 fl   Added getimage method\n# 96-11-01 fl   Rewritten, removed image attribute and crop method\n# 97-05-09 fl   Use PyImagingPaste method instead of image type\n# 97-05-12 fl   Minor tweaks to match the IFUNC95 interface\n# 97-05-17 fl   Support the \"pilbitmap\" booster patch\n# 97-06-05 fl   Added file= and data= argument to image constructors\n# 98-03-09 fl   Added width and height methods to Image classes\n# 98-07-02 fl   Use default mode for \"P\" images without palette attribute\n# 98-07-02 fl   Explicitly destroy Tkinter image objects\n# 99-07-24 fl   Support multiple Tk interpreters (from Greg Couch)\n# 99-07-26 fl   Automatically hook into Tkinter (if possible)\n# 99-08-15 fl   Hook uses _imagingtk instead of _imaging\n#\n# Copyright (c) 1997-1999 by Secret Labs AB\n# Copyright (c) 1996-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport tkinter\nimport warnings\nfrom io import BytesIO\n\nfrom . import Image\n\n# --------------------------------------------------------------------\n# Check for Tkinter interface hooks\n\n_pilbitmap_ok = None\n\n\ndef _pilbitmap_check():\n    global _pilbitmap_ok\n    if _pilbitmap_ok is None:\n        try:\n            im = Image.new(\"1\", (1, 1))\n            tkinter.BitmapImage(data=f\"PIL:{im.im.id}\")\n            _pilbitmap_ok = 1\n        except tkinter.TclError:\n            _pilbitmap_ok = 0\n    return _pilbitmap_ok\n\n\ndef _get_image_from_kw(kw):\n    source = None\n    if \"file\" in kw:\n        source = kw.pop(\"file\")\n    elif \"data\" in kw:\n        source = BytesIO(kw.pop(\"data\"))\n    if source:\n        return Image.open(source)\n\n\ndef _pyimagingtkcall(command, photo, id):\n    tk = photo.tk\n    try:\n        tk.call(command, photo, id)\n    except tkinter.TclError:\n        # activate Tkinter hook\n        # may raise an error if it cannot attach to Tkinter\n        from . import _imagingtk\n\n        try:\n            if hasattr(tk, \"interp\"):\n                # Required for PyPy, which always has CFFI installed\n                from cffi import FFI\n\n                ffi = FFI()\n\n                # PyPy is using an FFI CDATA element\n                # (Pdb) self.tk.interp\n                #  <cdata 'Tcl_Interp *' 0x3061b50>\n                _imagingtk.tkinit(int(ffi.cast(\"uintptr_t\", tk.interp)), 1)\n            else:\n                _imagingtk.tkinit(tk.interpaddr(), 1)\n        except AttributeError:\n            _imagingtk.tkinit(id(tk), 0)\n        tk.call(command, photo, id)\n\n\n# --------------------------------------------------------------------\n# PhotoImage\n\n\nclass PhotoImage:\n    \"\"\"\n    A Tkinter-compatible photo image.  This can be used\n    everywhere Tkinter expects an image object.  If the image is an RGBA\n    image, pixels having alpha 0 are treated as transparent.\n\n    The constructor takes either a PIL image, or a mode and a size.\n    Alternatively, you can use the ``file`` or ``data`` options to initialize\n    the photo image object.\n\n    :param image: Either a PIL image, or a mode string.  If a mode string is\n                  used, a size must also be given.\n    :param size: If the first argument is a mode string, this defines the size\n                 of the image.\n    :keyword file: A filename to load the image from (using\n                   ``Image.open(file)``).\n    :keyword data: An 8-bit string containing image data (as loaded from an\n                   image file).\n    \"\"\"\n\n    def __init__(self, image=None, size=None, **kw):\n\n        # Tk compatibility: file or data\n        if image is None:\n            image = _get_image_from_kw(kw)\n\n        if hasattr(image, \"mode\") and hasattr(image, \"size\"):\n            # got an image instead of a mode\n            mode = image.mode\n            if mode == \"P\":\n                # palette mapped data\n                image.load()\n                try:\n                    mode = image.palette.mode\n                except AttributeError:\n                    mode = \"RGB\"  # default\n            size = image.size\n            kw[\"width\"], kw[\"height\"] = size\n        else:\n            mode = image\n            image = None\n\n        if mode not in [\"1\", \"L\", \"RGB\", \"RGBA\"]:\n            mode = Image.getmodebase(mode)\n\n        self.__mode = mode\n        self.__size = size\n        self.__photo = tkinter.PhotoImage(**kw)\n        self.tk = self.__photo.tk\n        if image:\n            self.paste(image)\n\n    def __del__(self):\n        name = self.__photo.name\n        self.__photo.name = None\n        try:\n            self.__photo.tk.call(\"image\", \"delete\", name)\n        except Exception:\n            pass  # ignore internal errors\n\n    def __str__(self):\n        \"\"\"\n        Get the Tkinter photo image identifier.  This method is automatically\n        called by Tkinter whenever a PhotoImage object is passed to a Tkinter\n        method.\n\n        :return: A Tkinter photo image identifier (a string).\n        \"\"\"\n        return str(self.__photo)\n\n    def width(self):\n        \"\"\"\n        Get the width of the image.\n\n        :return: The width, in pixels.\n        \"\"\"\n        return self.__size[0]\n\n    def height(self):\n        \"\"\"\n        Get the height of the image.\n\n        :return: The height, in pixels.\n        \"\"\"\n        return self.__size[1]\n\n    def paste(self, im, box=None):\n        \"\"\"\n        Paste a PIL image into the photo image.  Note that this can\n        be very slow if the photo image is displayed.\n\n        :param im: A PIL image. The size must match the target region.  If the\n                   mode does not match, the image is converted to the mode of\n                   the bitmap image.\n        \"\"\"\n\n        if box is not None:\n            warnings.warn(\n                \"The box parameter is deprecated and will be removed in Pillow 10 \"\n                \"(2023-07-01).\",\n                DeprecationWarning,\n            )\n\n        # convert to blittable\n        im.load()\n        image = im.im\n        if image.isblock() and im.mode == self.__mode:\n            block = image\n        else:\n            block = image.new_block(self.__mode, im.size)\n            image.convert2(block, image)  # convert directly between buffers\n\n        _pyimagingtkcall(\"PyImagingPhoto\", self.__photo, block.id)\n\n\n# --------------------------------------------------------------------\n# BitmapImage\n\n\nclass BitmapImage:\n    \"\"\"\n    A Tkinter-compatible bitmap image.  This can be used everywhere Tkinter\n    expects an image object.\n\n    The given image must have mode \"1\".  Pixels having value 0 are treated as\n    transparent.  Options, if any, are passed on to Tkinter.  The most commonly\n    used option is ``foreground``, which is used to specify the color for the\n    non-transparent parts.  See the Tkinter documentation for information on\n    how to specify colours.\n\n    :param image: A PIL image.\n    \"\"\"\n\n    def __init__(self, image=None, **kw):\n\n        # Tk compatibility: file or data\n        if image is None:\n            image = _get_image_from_kw(kw)\n\n        self.__mode = image.mode\n        self.__size = image.size\n\n        if _pilbitmap_check():\n            # fast way (requires the pilbitmap booster patch)\n            image.load()\n            kw[\"data\"] = f\"PIL:{image.im.id}\"\n            self.__im = image  # must keep a reference\n        else:\n            # slow but safe way\n            kw[\"data\"] = image.tobitmap()\n        self.__photo = tkinter.BitmapImage(**kw)\n\n    def __del__(self):\n        name = self.__photo.name\n        self.__photo.name = None\n        try:\n            self.__photo.tk.call(\"image\", \"delete\", name)\n        except Exception:\n            pass  # ignore internal errors\n\n    def width(self):\n        \"\"\"\n        Get the width of the image.\n\n        :return: The width, in pixels.\n        \"\"\"\n        return self.__size[0]\n\n    def height(self):\n        \"\"\"\n        Get the height of the image.\n\n        :return: The height, in pixels.\n        \"\"\"\n        return self.__size[1]\n\n    def __str__(self):\n        \"\"\"\n        Get the Tkinter bitmap image identifier.  This method is automatically\n        called by Tkinter whenever a BitmapImage object is passed to a Tkinter\n        method.\n\n        :return: A Tkinter bitmap image identifier (a string).\n        \"\"\"\n        return str(self.__photo)\n\n\ndef getimage(photo):\n    \"\"\"Copies the contents of a PhotoImage to a PIL image memory.\"\"\"\n    im = Image.new(\"RGBA\", (photo.width(), photo.height()))\n    block = im.im\n\n    _pyimagingtkcall(\"PyImagingPhotoGet\", photo, block.id)\n\n    return im\n\n\ndef _show(image, title):\n    \"\"\"Helper for the Image.show method.\"\"\"\n\n    class UI(tkinter.Label):\n        def __init__(self, master, im):\n            if im.mode == \"1\":\n                self.image = BitmapImage(im, foreground=\"white\", master=master)\n            else:\n                self.image = PhotoImage(im, master=master)\n            super().__init__(master, image=self.image, bg=\"black\", bd=0)\n\n    if not tkinter._default_root:\n        raise OSError(\"tkinter not initialized\")\n    top = tkinter.Toplevel()\n    if title:\n        top.title(title)\n    UI(top, image).pack()\n", "path": "src/PIL/ImageTk.py"}]}