From 1f964ae256ac5369b5ad5323e79d63f5a655f958 Mon Sep 17 00:00:00 2001 From: TheLizzard Date: Wed, 22 Oct 2025 22:19:06 +0100 Subject: [PATCH] fixed misleading error and added `__contain__` method in `tkinter.Misc` --- Lib/test/test_tkinter/widget_tests.py | 2 ++ Lib/tkinter/__init__.py | 23 +++++++++++++++---- ...-10-22-22-18-12.gh-issue-140481.llKxYZ.rst | 1 + 3 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2025-10-22-22-18-12.gh-issue-140481.llKxYZ.rst diff --git a/Lib/test/test_tkinter/widget_tests.py b/Lib/test/test_tkinter/widget_tests.py index dd2d7c4da459ab..c0a7bd4c81ddd3 100644 --- a/Lib/test/test_tkinter/widget_tests.py +++ b/Lib/test/test_tkinter/widget_tests.py @@ -60,6 +60,8 @@ def checkParam(self, widget, name, value, *, expected=_sentinel, t = widget.configure(name) self.assertEqual(len(t), 5) self.assertEqual2(t[4], expected, eq=eq) + self.assertEqual(name in widget, True) + self.assertEqual("invalid-option-tkinter" in widget, False) def checkInvalidParam(self, widget, name, value, errmsg=None): orig = widget[name] diff --git a/Lib/tkinter/__init__.py b/Lib/tkinter/__init__.py index 9526d8b949fa3b..380c9b9666bffc 100644 --- a/Lib/tkinter/__init__.py +++ b/Lib/tkinter/__init__.py @@ -1845,10 +1845,18 @@ def configure(self, cnf=None, **kw): def cget(self, key): """Return the current value of the configuration option.""" - return self.tk.call(self._w, 'cget', '-' + key) + return self.tk.call(self._w, 'cget', f'-{key}') __getitem__ = cget + def __contains__(self, option): + """Check if the given option exists in this widget""" + try: + self.cget(option) + return True + except TclError: + return False + def __setitem__(self, key, value): self.configure({key: value}) @@ -4322,11 +4330,18 @@ def blank(self): def cget(self, option): """Return the value of OPTION.""" - return self.tk.call(self.name, 'cget', '-' + option) + return self.tk.call(self.name, 'cget', f'-{option}') # XXX config - def __getitem__(self, key): - return self.tk.call(self.name, 'cget', '-' + key) + __getitem__ = cget + + def __contains__(self, option): + """Check if the given option exists in this widget""" + try: + self.cget(option) + return True + except TclError: + return False def copy(self, *, from_coords=None, zoom=None, subsample=None): """Return a new PhotoImage with the same image as this widget. diff --git a/Misc/NEWS.d/next/Library/2025-10-22-22-18-12.gh-issue-140481.llKxYZ.rst b/Misc/NEWS.d/next/Library/2025-10-22-22-18-12.gh-issue-140481.llKxYZ.rst new file mode 100644 index 00000000000000..47e7859ff7a289 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-10-22-22-18-12.gh-issue-140481.llKxYZ.rst @@ -0,0 +1 @@ +fixed misleading error and added ``__contain__`` method in ``tkinter.Misc``