Skip to content

Commit 2b9878a

Browse files
gh-123193: Document tkinter Variable lifetime
A Tk variable wrapper unsets its Tcl variable when garbage collected, so a reference must be kept while a widget uses it. Otherwise Tk recreates the Tcl variable but never unsets it again, leaking it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 089e6f6 commit 2b9878a

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

Doc/library/tkinter.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,9 @@ method on it, and to change its value you call the :meth:`!set` method.
656656
If you follow this protocol, the widget will always track the value of the
657657
variable, with no further intervention on your part.
658658

659+
Keep a reference to the variable for as long as a widget uses it, for example
660+
by storing it as an attribute (see :class:`Variable`).
661+
659662
For example::
660663

661664
import tkinter as tk
@@ -5916,6 +5919,14 @@ Variable classes
59165919
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar` or
59175920
:class:`BooleanVar` -- rather than :class:`!Variable` directly.
59185921

5922+
.. note::
5923+
5924+
When a :class:`!Variable` is garbage collected, its Tcl variable is unset.
5925+
Keep a reference to it for as long as a widget is linked to it, for example
5926+
by storing it as an attribute rather than in a local variable.
5927+
Otherwise Tk recreates the Tcl variable to keep the widget working, but it
5928+
is never unset again, leaking one Tcl variable per dropped wrapper.
5929+
59195930
.. versionchanged:: 3.10
59205931
Two variables now compare equal (``==``) only when they have the same
59215932
name, are of the same class, and belong to the same Tcl interpreter.

0 commit comments

Comments
 (0)