Skip to content

Window

Usage

A window is the top-level container that the operating system uses to display widgets. On desktop platforms, an instance of Window will have a title bar, but will not have a menu or toolbar. On mobile, web and console platforms, Window is a bare container with no other decoration. Subclasses of Window (such as MainWindow) add other decorations.

When first created, a window is not visible. To display it, call the show() method. The title of the window will default to the formal name of the app.

The window has content, which will usually be a container widget of some kind. The content of the window can be changed by re-assigning its content attribute to a different widget.

import toga

window = toga.Window()
window.content = toga.Box(children=[...])
window.show()

# Change the window's content to something new
window.content = toga.Box(children=[...])

If the user attempts to close the window, Toga will call the on_close handler. This handler must return a bool confirming whether the close is permitted. This can be used to implement protections against closing a window with unsaved changes.

Once a window has been closed (either by user action, or programmatically with close()), it cannot be reused. The behavior of any method on a Window instance after it has been closed is undefined.

Notes

  • The operating system may provide controls that allow the user to resize, reposition, minimize, maximize or close the window. However, the availability of these controls is entirely operating system dependent.
  • While Toga provides methods for specifying the size and position of windows, these are ultimately at the discretion of the OS (or window manager). For example, on macOS, depending on a user's OS-level settings, new windows may open as tabs on the main window; on Linux, some window managers (e.g., tiling window managers) may not honor an app's size and position requests. You should avoid making UI design decisions that are dependent on specific size and placement of windows.
  • A mobile application can only have a single window (the main_window), and that window cannot be moved, resized, or hidden. Toga will raise an exception if you attempt to create a secondary window on a mobile platform. If you try to modify the size, position, or visibility of the main window, the request will be ignored.
  • On mobile platforms, a window's state cannot be WindowState.MINIMIZED or WindowState.MAXIMIZED. Any request to move to these states will be ignored.
  • On Linux, when using Wayland, a request to put a window into a WindowState.MINIMIZED state, or to restore from the WindowState.MINIMIZED state, will be ignored, and any associated events like on_hide() and on_show(), will not be triggered. This is due to limitations in window management features that Wayland allows apps to use.

Reference

Source code in core/src/toga/window.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
class Window:
    _WINDOW_CLASS = "Window"

    def __init__(
        self,
        id: str | None = None,
        title: str | None = None,
        position: PositionT | None = None,
        size: SizeT = (640, 480),
        resizable: bool = True,
        closable: bool = True,
        minimizable: bool = True,
        on_close: OnCloseHandler | None = None,
        on_gain_focus: OnGainFocusHandler | None = None,
        on_lose_focus: OnLoseFocusHandler | None = None,
        on_show: OnShowHandler | None = None,
        on_hide: OnHideHandler | None = None,
        on_resize: OnResizeHandler | None = None,
        content: Widget | None = None,
    ) -> None:
        """Create a new Window.

        :param id: A unique identifier for the window. If not provided, one will be
            automatically generated.
        :param title: Title for the window. Defaults to the formal name of the app.
        :param position: Position of the window, as a [`toga.Position`][] or tuple of
            `(x, y)` coordinates, in [CSS pixels][css-units].
        :param size: Size of the window, as a [`toga.Size`][] or tuple of `(width,
            height)`, in [CSS pixels][css-units].
        :param resizable: Can the window be resized by the user?
        :param closable: Can the window be closed by the user?
        :param minimizable: Can the window be minimized by the user?
        :param on_close: The initial [`on_close`][toga.Window.on_close] handler.
        :param content: The initial content for the window.
        """
        # Needs to be a late import to avoid circular dependencies.
        from toga import App

        self._id = str(id if id else identifier(self))
        self._impl: Any = None
        self._content: Widget | None = None
        self._closed = False

        self._resizable = resizable
        self._closable = closable
        self._minimizable = minimizable

        # The app needs to exist before windows are created. _app will only be None
        # until the window is added to the app below.
        self._app: App = None
        if App.app is None:
            raise RuntimeError("Cannot create a Window before creating an App")

        # Initialize event handlers to no-op defaults BEFORE creating the
        # implementation. Some platforms (Cocoa, .NET Framework 4.x WinForms)
        # fire resize / focus callbacks during impl construction, before the
        # explicit `self.on_X = ...` assignments below have run. Without these
        # defaults the dispatched callback raises AttributeError on
        # `self._on_resize` / `self._on_gain_focus` / etc.
        # See beeware/toga#4347 (resize during init on macOS) and #4357
        # (gain_focus on .NET Framework 4.x).
        self.on_close = None
        self.on_gain_focus = None
        self.on_lose_focus = None
        self.on_show = None
        self.on_hide = None
        self.on_resize = None

        self.factory = get_factory()
        self._impl = getattr(self.factory, self._WINDOW_CLASS)(
            interface=self,
            title=title if title else self._default_title,
            position=None if position is None else Position(*position),
            size=Size(*size),
        )

        # Add the window to the app
        App.app.windows.add(self)

        # If content has been provided, set it
        if content:
            self.content = content

        # Set up the event handlers on the interface (overrides the no-op
        # defaults installed above with the user-supplied handlers).
        self.on_close = on_close
        self.on_gain_focus = on_gain_focus
        self.on_lose_focus = on_lose_focus
        self.on_show = on_show
        self.on_hide = on_hide
        self.on_resize = on_resize

    def __lt__(self, other: Window) -> bool:
        return self.id < other.id

    ######################################################################
    # Window properties
    ######################################################################

    @property
    def app(self) -> App:
        """The [`App`][toga.App] that this window belongs to (read-only).

        New windows are automatically associated with the currently active app."""
        return self._app

    @app.setter
    def app(self, app: App) -> None:
        if self._app:
            raise ValueError("Window is already associated with an App")

        self._app = app
        self._impl.set_app(app._impl)

    @property
    def closable(self) -> bool:
        """Can the window be closed by the user?"""
        return self._closable

    @property
    def id(self) -> str:
        """A unique identifier for the window (read-only)."""
        return self._id

    @property
    def minimizable(self) -> bool:
        """Can the window be minimized by the user?"""
        return self._minimizable

    @property
    def resizable(self) -> bool:
        """Can the window be resized by the user?"""
        return self._resizable

    @property
    def _default_title(self) -> str:
        return toga.App.app.formal_name

    @property
    def title(self) -> str:
        """Title of the window. If no title is provided, the title will default to
        "Toga"."""
        return self._impl.get_title()

    @title.setter
    def title(self, title: str) -> None:
        if not title:
            title = self._default_title

        self._impl.set_title(str(title).split("\n")[0])

    ######################################################################
    # Window lifecycle
    ######################################################################

    def close(self) -> None:
        """Close the window.

        This *does not* invoke the `on_close` handler. If the window being closed
        is the app's main window, it will trigger `on_exit` handling; otherwise, the
        window will be immediately and unconditionally closed.

        Once a window has been closed, it *cannot* be reused. The behavior of any method
        or property on a [`Window`][toga.Window] instance after it has been closed is
        undefined, except for [`closed`][toga.Window.closed] which can be used to check
        if the window was closed.

        :returns: True if the window was actually closed; False if closing the window
            triggered `on_exit` handling.
        """
        close_window = True
        if self.app.main_window == self:
            # Closing the window marked as the main window is a request to exit.
            self.app.request_exit()
            close_window = False
        elif self.app.main_window is None:
            # If this is an app without a main window, the app is running, this
            # is the last window in the app, and the platform exits on last
            # window close, request an exit.
            if (
                len(self.app.windows) == 1
                and self.app._impl.CLOSE_ON_LAST_WINDOW
                and self.app.loop.is_running()
            ):
                self.app.request_exit()
                close_window = False

        if close_window:
            self._close()

        # Return whether the window was actually closed
        return close_window

    def _close(self):
        # The actual logic for closing a window. This is abstracted so that the testbed
        # can monkeypatch this method, recording the close request without actually
        # closing the app.
        if self.content:
            self.content.window = None
        self.app.windows.discard(self)
        self._impl.close()
        self._closed = True

    @property
    def closed(self) -> bool:
        """Whether the window was closed."""
        return self._closed

    def show(self) -> None:
        """Show the window. If the window is already visible, this method has no
        effect.

        :raises ValueError: If the window is currently in a minimized, full screen or
            presentation state.
        """
        if not self.visible:
            if self.state in {
                WindowState.MINIMIZED,
                WindowState.FULLSCREEN,
                WindowState.PRESENTATION,
            }:
                raise ValueError(f"A window in {self.state} state cannot be shown.")
            else:
                self._impl.show()

    ######################################################################
    # Window content and resources
    ######################################################################

    @property
    def content(self) -> Widget | None:
        """Content of the window. On setting, the content is added to the same app as
        the window."""
        return self._content

    @content.setter
    def content(self, widget: Widget) -> None:
        # Set window of old content to None
        if self._content:
            self._content.window = None

        # Assign the content widget to the same app as the window.
        widget.app = self.app

        # Assign the content widget to the window.
        widget.window = self

        # Track our new content
        self._content = widget

        # Manifest the widget
        self._impl.set_content(widget._impl)

        # Update the geometry of the widget
        widget.refresh()

    @property
    def widgets(self) -> FilteredWidgetRegistry:
        """The widgets contained in the window.

        Can be used to look up widgets by ID (e.g., `window.widgets["my_id"]`).
        """
        return FilteredWidgetRegistry(self)

    ######################################################################
    # Window size
    ######################################################################

    @property
    def size(self) -> Size:
        """Size of the window, in [CSS pixels][css-units].

        :raises RuntimeError: If resize is requested while in
            [`WindowState.FULLSCREEN`][toga.constants.WindowState.FULLSCREEN] or
            [`WindowState.PRESENTATION`][toga.constants.WindowState.PRESENTATION].
        """
        return self._impl.get_size()

    @size.setter
    def size(self, size: SizeT) -> None:
        if self.state in {WindowState.FULLSCREEN, WindowState.PRESENTATION}:
            raise RuntimeError(f"Cannot resize window while in {self.state}")
        elif self.size != size:
            self._impl.set_size(size)
            if self.content:
                self.content.refresh()

    ######################################################################
    # Window position
    ######################################################################

    @property
    def position(self) -> Position:
        """Absolute position of the window, in [CSS pixels][css-units].

        The origin is the top left corner of the primary screen.

        :raises RuntimeError: If position change is requested while in
            [`WindowState.FULLSCREEN`][toga.constants.WindowState.FULLSCREEN] or
            [`WindowState.PRESENTATION`][toga.constants.WindowState.PRESENTATION].
        """
        absolute_origin = self._app.screens[0].origin
        absolute_window_position = self._impl.get_position()
        window_position = absolute_window_position - absolute_origin

        return window_position

    @position.setter
    def position(self, position: PositionT) -> None:
        if self.state in {WindowState.FULLSCREEN, WindowState.PRESENTATION}:
            raise RuntimeError(f"Cannot change window position while in {self.state}")
        absolute_origin = self._app.screens[0].origin
        absolute_new_position = Position(*position) + absolute_origin
        self._impl.set_position(absolute_new_position)

    @property
    def screen(self) -> Screen:
        """Instance of the [`toga.Screen`][toga.screens.Screen] on which this window
        is present."""
        return self._impl.get_current_screen().interface

    @screen.setter
    def screen(self, app_screen: Screen) -> None:
        original_window_location = self.position
        original_origin = self.screen.origin
        new_origin = app_screen.origin
        self._impl.set_position(original_window_location - original_origin + new_origin)

    @property
    def screen_position(self) -> Position:
        """Position of the window with respect to current screen, in
        [CSS pixels][css-units].

        :raises RuntimeError: If position change is requested while in
            [`WindowState.FULLSCREEN`][toga.constants.WindowState.FULLSCREEN] or
            [`WindowState.PRESENTATION`][toga.constants.WindowState.PRESENTATION].
        """
        return self.position - self.screen.origin

    @screen_position.setter
    def screen_position(self, position: PositionT) -> None:
        if self.state in {WindowState.FULLSCREEN, WindowState.PRESENTATION}:
            raise RuntimeError(f"Cannot change window position while in {self.state}")
        new_relative_position = Position(*position) + self.screen.origin
        self._impl.set_position(new_relative_position)

    ######################################################################
    # Window visibility
    ######################################################################

    def hide(self) -> None:
        """Hide the window. If the window is already hidden, this method has no
        effect.

        :raises ValueError: If the window is currently in a minimized, full screen or
            presentation state.
        """
        if self.visible:
            if self.state in {
                WindowState.MINIMIZED,
                WindowState.FULLSCREEN,
                WindowState.PRESENTATION,
            }:
                raise ValueError(f"A window in {self.state} state cannot be hidden.")
            else:
                self._impl.hide()

    @property
    def visible(self) -> bool:
        """Is the window visible?"""
        return self._impl.get_visible()

    @visible.setter
    def visible(self, visible: bool) -> None:
        if visible:
            self.show()
        else:
            self.hide()

    ######################################################################
    # Window state
    ######################################################################

    @property
    def state(self) -> WindowState:
        """The current state of the window.

        When the window is in transition, then this will return the state it
        is transitioning towards, instead of the actual instantaneous state.

        :raises RuntimeError: If state change is requested while the window is
            hidden.

        :raises ValueError: If any state other than
            [`WindowState.MINIMIZED`][toga.constants.WindowState.MINIMIZED]
            or [`WindowState.NORMAL`][toga.constants.WindowState.NORMAL]
            is requested on a non-resizable window.
        """
        # There are 2 types of window states that we can get from the backend:
        # * The instantaneous state -- Used internally on implementation side
        # * The in-progress state -- Used for same state checking on the core
        #                            and for the public API.
        return self._impl.get_window_state(in_progress_state=True)

    @state.setter
    def state(self, state: WindowState) -> None:
        if not self.visible:
            raise RuntimeError("Window state of a hidden window cannot be changed.")
        elif not self.resizable and state in {
            WindowState.MAXIMIZED,
            WindowState.FULLSCREEN,
            WindowState.PRESENTATION,
        }:
            raise ValueError(
                f"A non-resizable window cannot be set to a state of {state}."
            )
        else:
            if self.state != state:
                self._impl.set_window_state(state)

    ######################################################################
    # Window capabilities
    ######################################################################

    def as_image(self, format: type[ImageT] = Image) -> ImageT:
        """Render the current contents of the window as an image.

        :param format: Format to provide. Defaults to [`Image`][toga.images.Image]; also
            supports [`PIL.Image.Image`][] if Pillow is installed, as well as any image
            types defined by installed
            [image format plugins](/reference/api/resources/image/image-format-plugins.md).
        :returns: An image containing the window content, in the format requested.
        """  # noqa: E501
        return Image(self._impl.get_image_data()).as_format(format)

    async def dialog(
        self, dialog: dialogs.Dialog[dialogs.DialogResultT]
    ) -> dialogs.DialogResultT:
        """Display a dialog to the user, modal to this window.

        :param dialog: The
            [toga.Window.dialog](/reference/api/application/dialogs.md) to
            display to the user.
        :returns: The result of the dialog.
        """
        return await dialog._show(self)

    ######################################################################
    # Window events
    ######################################################################

    @property
    def on_close(self) -> OnCloseHandler | None:
        """The handler to invoke if the user attempts to close the window."""
        return self._on_close

    @on_close.setter
    def on_close(self, handler: OnCloseHandler | None) -> None:
        def cleanup(window: Window, should_close: bool) -> None:
            if should_close or handler is None:
                window.close()

        self._on_close = wrapped_handler(self, handler, cleanup=cleanup)

    @property
    def on_gain_focus(self) -> callable:
        """The handler to invoke if the window gains input focus."""
        return self._on_gain_focus

    @on_gain_focus.setter
    def on_gain_focus(self, handler):
        self._on_gain_focus = wrapped_handler(self, handler)

    @property
    def on_lose_focus(self) -> callable:
        """The handler to invoke if the window loses input focus."""
        return self._on_lose_focus

    @on_lose_focus.setter
    def on_lose_focus(self, handler):
        self._on_lose_focus = wrapped_handler(self, handler)

    @property
    def on_show(self) -> callable:
        """The handler to invoke if the window is shown from a hidden state."""
        return self._on_show

    @on_show.setter
    def on_show(self, handler):
        self._on_show = wrapped_handler(self, handler)

    @property
    def on_hide(self) -> callable:
        """The handler to invoke if the window is hidden from a visible state."""
        return self._on_hide

    @on_hide.setter
    def on_hide(self, handler):
        self._on_hide = wrapped_handler(self, handler)

    @property
    def on_resize(self) -> OnResizeHandler:
        """The handler to invoke when the window resizes."""
        return self._on_resize

    @on_resize.setter
    def on_resize(self, handler):
        self._on_resize = wrapped_handler(self, handler)

    ######################################################################
    # 2024-06: Backwards compatibility for <= 0.4.5
    ######################################################################

    def info_dialog(
        self,
        title: str,
        message: str,
        on_result: DialogResultHandler[None] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
        [`InfoDialog`][toga.InfoDialog]"""
        warnings.warn(
            "info_dialog(...) has been deprecated; use dialog(toga.InfoDialog(...))",
            DeprecationWarning,
            stacklevel=2,
        )

        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.InfoDialog(title, message)
        result.dialog._impl.show(self, result)
        return result

    def question_dialog(
        self,
        title: str,
        message: str,
        on_result: DialogResultHandler[bool] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
        [`QuestionDialog`][toga.QuestionDialog]"""
        warnings.warn(
            (
                "question_dialog(...) has been deprecated; "
                "use dialog(toga.QuestionDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )

        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.QuestionDialog(title, message)
        result.dialog._impl.show(self, result)
        return result

    def confirm_dialog(
        self,
        title: str,
        message: str,
        on_result: DialogResultHandler[bool] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
        [`ConfirmDialog`][toga.ConfirmDialog]"""
        warnings.warn(
            (
                "confirm_dialog(...) has been deprecated; "
                "use dialog(toga.ConfirmDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )

        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.ConfirmDialog(title, message)
        result.dialog._impl.show(self, result)
        return result

    def error_dialog(
        self,
        title: str,
        message: str,
        on_result: DialogResultHandler[None] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
        [`ErrorDialog`][toga.ErrorDialog]"""
        warnings.warn(
            "error_dialog(...) has been deprecated; use dialog(toga.ErrorDialog(...))",
            DeprecationWarning,
            stacklevel=2,
        )

        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.ErrorDialog(title, message)
        result.dialog._impl.show(self, result)
        return result

    def stack_trace_dialog(
        self,
        title: str,
        message: str,
        content: str,
        retry: bool = False,
        on_result: DialogResultHandler[bool] | DialogResultHandler[None] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
        [`StackTraceDialog`][toga.StackTraceDialog]"""
        warnings.warn(
            (
                "stack_trace_dialog(...) has been deprecated; "
                "use dialog(toga.StackTraceDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )

        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.StackTraceDialog(
            title,
            message=message,
            content=content,
            retry=retry,
        )
        result.dialog._impl.show(self, result)
        return result

    def save_file_dialog(
        self,
        title: str,
        suggested_filename: Path | str,
        file_types: list[str] | None = None,
        on_result: DialogResultHandler[Path | None] | None = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
        [`SaveFileDialog`][toga.SaveFileDialog]"""
        warnings.warn(
            (
                "save_file_dialog(...) has been deprecated; "
                "use dialog(toga.SaveFileDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.SaveFileDialog(
            title,
            suggested_filename=suggested_filename,
            file_types=file_types,
        )
        result.dialog._impl.show(self, result)
        return result

    def open_file_dialog(
        self,
        title: str,
        initial_directory: Path | str | None = None,
        file_types: list[str] | None = None,
        multiple_select: bool = False,
        on_result: (
            DialogResultHandler[list[Path]]
            | DialogResultHandler[Path]
            | DialogResultHandler[None]
            | None
        ) = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
        [`OpenFileDialog`][toga.OpenFileDialog]"""
        warnings.warn(
            (
                "open_file_dialog(...) has been deprecated; "
                "use dialog(toga.OpenFileDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.OpenFileDialog(
            title,
            initial_directory=initial_directory,
            file_types=file_types,
            multiple_select=multiple_select,
        )
        result.dialog._impl.show(self, result)
        return result

    def select_folder_dialog(
        self,
        title: str,
        initial_directory: Path | str | None = None,
        multiple_select: bool = False,
        on_result: (
            DialogResultHandler[list[Path]]
            | DialogResultHandler[Path]
            | DialogResultHandler[None]
            | None
        ) = None,
    ) -> Dialog:
        """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
        [`SelectFolderDialog`][toga.SelectFolderDialog]"""
        warnings.warn(
            (
                "select_folder_dialog(...) has been deprecated; "
                "use dialog(toga.SelectFolderDialog(...))"
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        result = Dialog(
            self,
            on_result=wrapped_handler(self, on_result) if on_result else None,
        )
        result.dialog = dialogs.SelectFolderDialog(
            title,
            initial_directory=initial_directory,
            multiple_select=multiple_select,
        )
        result.dialog._impl.show(self, result)
        return result

    ######################################################################
    # End backwards compatibility
    ######################################################################

    ######################################################################
    # 2024-10: Backwards compatibility for < 0.5.0
    ######################################################################
    @property
    def full_screen(self) -> bool:
        """**DEPRECATED** – Use [`Window.state`][toga.Window.state]."""
        warnings.warn(
            "`Window.full_screen` is deprecated. Use `Window.state` instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return bool(self.state == WindowState.FULLSCREEN)

    @full_screen.setter
    def full_screen(self, is_full_screen: bool) -> None:
        warnings.warn(
            "`Window.full_screen` is deprecated. Use `Window.state` instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        target_state = WindowState.FULLSCREEN if is_full_screen else WindowState.NORMAL
        if self.state != target_state:
            self._impl.set_window_state(target_state)

app property writable

The App that this window belongs to (read-only).

New windows are automatically associated with the currently active app.

closable property

Can the window be closed by the user?

closed property

Whether the window was closed.

content property writable

Content of the window. On setting, the content is added to the same app as the window.

full_screen property writable

DEPRECATED – Use Window.state.

id property

A unique identifier for the window (read-only).

minimizable property

Can the window be minimized by the user?

on_close property writable

The handler to invoke if the user attempts to close the window.

on_gain_focus property writable

The handler to invoke if the window gains input focus.

on_hide property writable

The handler to invoke if the window is hidden from a visible state.

on_lose_focus property writable

The handler to invoke if the window loses input focus.

on_resize property writable

The handler to invoke when the window resizes.

on_show property writable

The handler to invoke if the window is shown from a hidden state.

position property writable

Absolute position of the window, in CSS pixels.

The origin is the top left corner of the primary screen.

:raises RuntimeError: If position change is requested while in WindowState.FULLSCREEN or WindowState.PRESENTATION.

resizable property

Can the window be resized by the user?

screen property writable

Instance of the toga.Screen on which this window is present.

screen_position property writable

Position of the window with respect to current screen, in CSS pixels.

:raises RuntimeError: If position change is requested while in WindowState.FULLSCREEN or WindowState.PRESENTATION.

size property writable

Size of the window, in CSS pixels.

:raises RuntimeError: If resize is requested while in WindowState.FULLSCREEN or WindowState.PRESENTATION.

state property writable

The current state of the window.

When the window is in transition, then this will return the state it is transitioning towards, instead of the actual instantaneous state.

:raises RuntimeError: If state change is requested while the window is hidden.

:raises ValueError: If any state other than WindowState.MINIMIZED or WindowState.NORMAL is requested on a non-resizable window.

title property writable

Title of the window. If no title is provided, the title will default to "Toga".

visible property writable

Is the window visible?

widgets property

The widgets contained in the window.

Can be used to look up widgets by ID (e.g., window.widgets["my_id"]).

__init__(id=None, title=None, position=None, size=(640, 480), resizable=True, closable=True, minimizable=True, on_close=None, on_gain_focus=None, on_lose_focus=None, on_show=None, on_hide=None, on_resize=None, content=None)

Create a new Window.

:param id: A unique identifier for the window. If not provided, one will be automatically generated. :param title: Title for the window. Defaults to the formal name of the app. :param position: Position of the window, as a toga.Position or tuple of (x, y) coordinates, in CSS pixels. :param size: Size of the window, as a toga.Size or tuple of (width, height), in CSS pixels. :param resizable: Can the window be resized by the user? :param closable: Can the window be closed by the user? :param minimizable: Can the window be minimized by the user? :param on_close: The initial on_close handler. :param content: The initial content for the window.

Source code in core/src/toga/window.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def __init__(
    self,
    id: str | None = None,
    title: str | None = None,
    position: PositionT | None = None,
    size: SizeT = (640, 480),
    resizable: bool = True,
    closable: bool = True,
    minimizable: bool = True,
    on_close: OnCloseHandler | None = None,
    on_gain_focus: OnGainFocusHandler | None = None,
    on_lose_focus: OnLoseFocusHandler | None = None,
    on_show: OnShowHandler | None = None,
    on_hide: OnHideHandler | None = None,
    on_resize: OnResizeHandler | None = None,
    content: Widget | None = None,
) -> None:
    """Create a new Window.

    :param id: A unique identifier for the window. If not provided, one will be
        automatically generated.
    :param title: Title for the window. Defaults to the formal name of the app.
    :param position: Position of the window, as a [`toga.Position`][] or tuple of
        `(x, y)` coordinates, in [CSS pixels][css-units].
    :param size: Size of the window, as a [`toga.Size`][] or tuple of `(width,
        height)`, in [CSS pixels][css-units].
    :param resizable: Can the window be resized by the user?
    :param closable: Can the window be closed by the user?
    :param minimizable: Can the window be minimized by the user?
    :param on_close: The initial [`on_close`][toga.Window.on_close] handler.
    :param content: The initial content for the window.
    """
    # Needs to be a late import to avoid circular dependencies.
    from toga import App

    self._id = str(id if id else identifier(self))
    self._impl: Any = None
    self._content: Widget | None = None
    self._closed = False

    self._resizable = resizable
    self._closable = closable
    self._minimizable = minimizable

    # The app needs to exist before windows are created. _app will only be None
    # until the window is added to the app below.
    self._app: App = None
    if App.app is None:
        raise RuntimeError("Cannot create a Window before creating an App")

    # Initialize event handlers to no-op defaults BEFORE creating the
    # implementation. Some platforms (Cocoa, .NET Framework 4.x WinForms)
    # fire resize / focus callbacks during impl construction, before the
    # explicit `self.on_X = ...` assignments below have run. Without these
    # defaults the dispatched callback raises AttributeError on
    # `self._on_resize` / `self._on_gain_focus` / etc.
    # See beeware/toga#4347 (resize during init on macOS) and #4357
    # (gain_focus on .NET Framework 4.x).
    self.on_close = None
    self.on_gain_focus = None
    self.on_lose_focus = None
    self.on_show = None
    self.on_hide = None
    self.on_resize = None

    self.factory = get_factory()
    self._impl = getattr(self.factory, self._WINDOW_CLASS)(
        interface=self,
        title=title if title else self._default_title,
        position=None if position is None else Position(*position),
        size=Size(*size),
    )

    # Add the window to the app
    App.app.windows.add(self)

    # If content has been provided, set it
    if content:
        self.content = content

    # Set up the event handlers on the interface (overrides the no-op
    # defaults installed above with the user-supplied handlers).
    self.on_close = on_close
    self.on_gain_focus = on_gain_focus
    self.on_lose_focus = on_lose_focus
    self.on_show = on_show
    self.on_hide = on_hide
    self.on_resize = on_resize

as_image(format=Image)

Render the current contents of the window as an image.

:param format: Format to provide. Defaults to Image; also supports [PIL.Image.Image][] if Pillow is installed, as well as any image types defined by installed image format plugins. :returns: An image containing the window content, in the format requested.

Source code in core/src/toga/window.py
626
627
628
629
630
631
632
633
634
635
def as_image(self, format: type[ImageT] = Image) -> ImageT:
    """Render the current contents of the window as an image.

    :param format: Format to provide. Defaults to [`Image`][toga.images.Image]; also
        supports [`PIL.Image.Image`][] if Pillow is installed, as well as any image
        types defined by installed
        [image format plugins](/reference/api/resources/image/image-format-plugins.md).
    :returns: An image containing the window content, in the format requested.
    """  # noqa: E501
    return Image(self._impl.get_image_data()).as_format(format)

close()

Close the window.

This does not invoke the on_close handler. If the window being closed is the app's main window, it will trigger on_exit handling; otherwise, the window will be immediately and unconditionally closed.

Once a window has been closed, it cannot be reused. The behavior of any method or property on a Window instance after it has been closed is undefined, except for closed which can be used to check if the window was closed.

:returns: True if the window was actually closed; False if closing the window triggered on_exit handling.

Source code in core/src/toga/window.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def close(self) -> None:
    """Close the window.

    This *does not* invoke the `on_close` handler. If the window being closed
    is the app's main window, it will trigger `on_exit` handling; otherwise, the
    window will be immediately and unconditionally closed.

    Once a window has been closed, it *cannot* be reused. The behavior of any method
    or property on a [`Window`][toga.Window] instance after it has been closed is
    undefined, except for [`closed`][toga.Window.closed] which can be used to check
    if the window was closed.

    :returns: True if the window was actually closed; False if closing the window
        triggered `on_exit` handling.
    """
    close_window = True
    if self.app.main_window == self:
        # Closing the window marked as the main window is a request to exit.
        self.app.request_exit()
        close_window = False
    elif self.app.main_window is None:
        # If this is an app without a main window, the app is running, this
        # is the last window in the app, and the platform exits on last
        # window close, request an exit.
        if (
            len(self.app.windows) == 1
            and self.app._impl.CLOSE_ON_LAST_WINDOW
            and self.app.loop.is_running()
        ):
            self.app.request_exit()
            close_window = False

    if close_window:
        self._close()

    # Return whether the window was actually closed
    return close_window

confirm_dialog(title, message, on_result=None)

DEPRECATED - await dialog() with a ConfirmDialog

Source code in core/src/toga/window.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def confirm_dialog(
    self,
    title: str,
    message: str,
    on_result: DialogResultHandler[bool] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
    [`ConfirmDialog`][toga.ConfirmDialog]"""
    warnings.warn(
        (
            "confirm_dialog(...) has been deprecated; "
            "use dialog(toga.ConfirmDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )

    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.ConfirmDialog(title, message)
    result.dialog._impl.show(self, result)
    return result

dialog(dialog) async

Display a dialog to the user, modal to this window.

:param dialog: The toga.Window.dialog to display to the user. :returns: The result of the dialog.

Source code in core/src/toga/window.py
637
638
639
640
641
642
643
644
645
646
647
async def dialog(
    self, dialog: dialogs.Dialog[dialogs.DialogResultT]
) -> dialogs.DialogResultT:
    """Display a dialog to the user, modal to this window.

    :param dialog: The
        [toga.Window.dialog](/reference/api/application/dialogs.md) to
        display to the user.
    :returns: The result of the dialog.
    """
    return await dialog._show(self)

error_dialog(title, message, on_result=None)

DEPRECATED - await dialog() with an ErrorDialog

Source code in core/src/toga/window.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def error_dialog(
    self,
    title: str,
    message: str,
    on_result: DialogResultHandler[None] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
    [`ErrorDialog`][toga.ErrorDialog]"""
    warnings.warn(
        "error_dialog(...) has been deprecated; use dialog(toga.ErrorDialog(...))",
        DeprecationWarning,
        stacklevel=2,
    )

    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.ErrorDialog(title, message)
    result.dialog._impl.show(self, result)
    return result

hide()

Hide the window. If the window is already hidden, this method has no effect.

:raises ValueError: If the window is currently in a minimized, full screen or presentation state.

Source code in core/src/toga/window.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
def hide(self) -> None:
    """Hide the window. If the window is already hidden, this method has no
    effect.

    :raises ValueError: If the window is currently in a minimized, full screen or
        presentation state.
    """
    if self.visible:
        if self.state in {
            WindowState.MINIMIZED,
            WindowState.FULLSCREEN,
            WindowState.PRESENTATION,
        }:
            raise ValueError(f"A window in {self.state} state cannot be hidden.")
        else:
            self._impl.hide()

info_dialog(title, message, on_result=None)

DEPRECATED - await dialog() with an InfoDialog

Source code in core/src/toga/window.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def info_dialog(
    self,
    title: str,
    message: str,
    on_result: DialogResultHandler[None] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
    [`InfoDialog`][toga.InfoDialog]"""
    warnings.warn(
        "info_dialog(...) has been deprecated; use dialog(toga.InfoDialog(...))",
        DeprecationWarning,
        stacklevel=2,
    )

    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.InfoDialog(title, message)
    result.dialog._impl.show(self, result)
    return result

open_file_dialog(title, initial_directory=None, file_types=None, multiple_select=False, on_result=None)

DEPRECATED - await dialog() with an OpenFileDialog

Source code in core/src/toga/window.py
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
def open_file_dialog(
    self,
    title: str,
    initial_directory: Path | str | None = None,
    file_types: list[str] | None = None,
    multiple_select: bool = False,
    on_result: (
        DialogResultHandler[list[Path]]
        | DialogResultHandler[Path]
        | DialogResultHandler[None]
        | None
    ) = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with an
    [`OpenFileDialog`][toga.OpenFileDialog]"""
    warnings.warn(
        (
            "open_file_dialog(...) has been deprecated; "
            "use dialog(toga.OpenFileDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )
    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.OpenFileDialog(
        title,
        initial_directory=initial_directory,
        file_types=file_types,
        multiple_select=multiple_select,
    )
    result.dialog._impl.show(self, result)
    return result

question_dialog(title, message, on_result=None)

DEPRECATED - await dialog() with a QuestionDialog

Source code in core/src/toga/window.py
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def question_dialog(
    self,
    title: str,
    message: str,
    on_result: DialogResultHandler[bool] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
    [`QuestionDialog`][toga.QuestionDialog]"""
    warnings.warn(
        (
            "question_dialog(...) has been deprecated; "
            "use dialog(toga.QuestionDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )

    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.QuestionDialog(title, message)
    result.dialog._impl.show(self, result)
    return result

save_file_dialog(title, suggested_filename, file_types=None, on_result=None)

DEPRECATED - await dialog() with a SaveFileDialog

Source code in core/src/toga/window.py
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
def save_file_dialog(
    self,
    title: str,
    suggested_filename: Path | str,
    file_types: list[str] | None = None,
    on_result: DialogResultHandler[Path | None] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
    [`SaveFileDialog`][toga.SaveFileDialog]"""
    warnings.warn(
        (
            "save_file_dialog(...) has been deprecated; "
            "use dialog(toga.SaveFileDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )
    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.SaveFileDialog(
        title,
        suggested_filename=suggested_filename,
        file_types=file_types,
    )
    result.dialog._impl.show(self, result)
    return result

select_folder_dialog(title, initial_directory=None, multiple_select=False, on_result=None)

DEPRECATED - await dialog() with a SelectFolderDialog

Source code in core/src/toga/window.py
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
def select_folder_dialog(
    self,
    title: str,
    initial_directory: Path | str | None = None,
    multiple_select: bool = False,
    on_result: (
        DialogResultHandler[list[Path]]
        | DialogResultHandler[Path]
        | DialogResultHandler[None]
        | None
    ) = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
    [`SelectFolderDialog`][toga.SelectFolderDialog]"""
    warnings.warn(
        (
            "select_folder_dialog(...) has been deprecated; "
            "use dialog(toga.SelectFolderDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )
    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.SelectFolderDialog(
        title,
        initial_directory=initial_directory,
        multiple_select=multiple_select,
    )
    result.dialog._impl.show(self, result)
    return result

show()

Show the window. If the window is already visible, this method has no effect.

:raises ValueError: If the window is currently in a minimized, full screen or presentation state.

Source code in core/src/toga/window.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def show(self) -> None:
    """Show the window. If the window is already visible, this method has no
    effect.

    :raises ValueError: If the window is currently in a minimized, full screen or
        presentation state.
    """
    if not self.visible:
        if self.state in {
            WindowState.MINIMIZED,
            WindowState.FULLSCREEN,
            WindowState.PRESENTATION,
        }:
            raise ValueError(f"A window in {self.state} state cannot be shown.")
        else:
            self._impl.show()

stack_trace_dialog(title, message, content, retry=False, on_result=None)

DEPRECATED - await dialog() with a StackTraceDialog

Source code in core/src/toga/window.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
def stack_trace_dialog(
    self,
    title: str,
    message: str,
    content: str,
    retry: bool = False,
    on_result: DialogResultHandler[bool] | DialogResultHandler[None] | None = None,
) -> Dialog:
    """**DEPRECATED** - await [`dialog()`][toga.Window.dialog] with a
    [`StackTraceDialog`][toga.StackTraceDialog]"""
    warnings.warn(
        (
            "stack_trace_dialog(...) has been deprecated; "
            "use dialog(toga.StackTraceDialog(...))"
        ),
        DeprecationWarning,
        stacklevel=2,
    )

    result = Dialog(
        self,
        on_result=wrapped_handler(self, on_result) if on_result else None,
    )
    result.dialog = dialogs.StackTraceDialog(
        title,
        message=message,
        content=content,
        retry=retry,
    )
    result.dialog._impl.show(self, result)
    return result

Bases: MutableSet[Window]

Source code in core/src/toga/window.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
class WindowSet(MutableSet[Window]):
    def __init__(self, app: App):
        """A collection of windows managed by an app.

        A window is automatically added to the app when it is created, and removed when
        it is closed. Adding a window to an App's window set automatically sets the
        [`Window.app`][toga.Window.app] property of the Window.
        """
        self.app = app
        self.elements: set[Window] = set()

    def add(self, window: Window) -> None:
        if not isinstance(window, Window):
            raise TypeError("Can only add objects of type toga.Window")
        # Silently not add if duplicate
        if window not in self.elements:
            self.elements.add(window)
            window.app = self.app

    def discard(self, window: Window) -> None:
        if not isinstance(window, Window):
            raise TypeError("Can only discard objects of type toga.Window")
        if window not in self.elements:
            raise ValueError(f"{window!r} is not part of this app")
        self.elements.remove(window)

    def __iter__(self) -> Iterator[Window]:
        return iter(self.elements)

    def __contains__(self, value: object) -> bool:
        return value in self.elements

    def __len__(self) -> int:
        return len(self.elements)

__init__(app)

A collection of windows managed by an app.

A window is automatically added to the app when it is created, and removed when it is closed. Adding a window to an App's window set automatically sets the Window.app property of the Window.

Source code in core/src/toga/window.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
def __init__(self, app: App):
    """A collection of windows managed by an app.

    A window is automatically added to the app when it is created, and removed when
    it is closed. Adding a window to an App's window set automatically sets the
    [`Window.app`][toga.Window.app] property of the Window.
    """
    self.app = app
    self.elements: set[Window] = set()

Bases: AsyncResult

Source code in core/src/toga/window.py
193
194
195
196
197
198
199
class Dialog(AsyncResult):
    RESULT_TYPE = "dialog"

    def __init__(self, window: Window, on_result: DialogResultHandler[Any]):
        super().__init__(on_result=on_result)
        self.window = window
        self.app = window.app

Bases: Protocol

Source code in core/src/toga/window.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class OnCloseHandler(Protocol):
    def __call__(self, window: Window, **kwargs: Any) -> bool:
        """A handler to invoke when a window is about to close.

        The return value of this callback controls whether the window
        is allowed to close.
        This can be used to prevent a window closing with unsaved changes, etc.

        :param window: The window instance that is closing.
        :param kwargs: Ensures compatibility with arguments added in future versions.
        :returns: `True` if the window is allowed to close; `False` if the window
            is not allowed to close.
        """
        ...

__call__(window, **kwargs)

A handler to invoke when a window is about to close.

The return value of this callback controls whether the window is allowed to close. This can be used to prevent a window closing with unsaved changes, etc.

:param window: The window instance that is closing. :param kwargs: Ensures compatibility with arguments added in future versions. :returns: True if the window is allowed to close; False if the window is not allowed to close.

Source code in core/src/toga/window.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __call__(self, window: Window, **kwargs: Any) -> bool:
    """A handler to invoke when a window is about to close.

    The return value of this callback controls whether the window
    is allowed to close.
    This can be used to prevent a window closing with unsaved changes, etc.

    :param window: The window instance that is closing.
    :param kwargs: Ensures compatibility with arguments added in future versions.
    :returns: `True` if the window is allowed to close; `False` if the window
        is not allowed to close.
    """
    ...

Bases: Protocol[_DialogResultT]

Source code in core/src/toga/window.py
183
184
185
186
187
188
189
190
class DialogResultHandler(Protocol[_DialogResultT]):
    def __call__(self, window: Window, result: _DialogResultT, **kwargs: Any) -> object:
        """A handler to invoke when a dialog is closed.

        :param window: The window that opened the dialog.
        :param result: The result returned by the dialog.
        :param kwargs: Ensures compatibility with arguments added in future versions.
        """

__call__(window, result, **kwargs)

A handler to invoke when a dialog is closed.

:param window: The window that opened the dialog. :param result: The result returned by the dialog. :param kwargs: Ensures compatibility with arguments added in future versions.

Source code in core/src/toga/window.py
184
185
186
187
188
189
190
def __call__(self, window: Window, result: _DialogResultT, **kwargs: Any) -> object:
    """A handler to invoke when a dialog is closed.

    :param window: The window that opened the dialog.
    :param result: The result returned by the dialog.
    :param kwargs: Ensures compatibility with arguments added in future versions.
    """