Skip to content

Commit f8ad1a9

Browse files
pythongh-75666: Tkinter: "unbind(sequence, funcid)" now only unbinds "funcid"
Previously, "widget.unbind(sequence, funcid)" destroyed the current binding for "sequence", leaving "sequence" unbound, and deleted the "funcid" command. Now it removes only "funcid" from the binding for "sequence", keeping other commands, and deletes the "funcid" command. It leaves "sequence" unbound only if "funcid" was the last bound command. Co-authored-by: GiovanniL <[email protected]>
1 parent 9da98c0 commit f8ad1a9

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

Lib/test/test_tkinter/test_misc.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,8 @@ def test2(e): pass
491491
f.unbind(event, funcid)
492492
script = f.bind(event)
493493
self.assertNotIn(funcid, script)
494+
self.assertIn(funcid2, script)
495+
self.assertEqual(f.bind(), (event,))
494496
self.assertCommandNotExist(funcid)
495497
self.assertCommandExist(funcid2)
496498

Lib/tkinter/__init__.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,10 +1527,21 @@ def bind(self, sequence=None, func=None, add=None):
15271527
return self._bind(('bind', self._w), sequence, func, add)
15281528

15291529
def unbind(self, sequence, funcid=None):
1530-
"""Unbind for this widget for event SEQUENCE the
1531-
function identified with FUNCID."""
1532-
self.tk.call('bind', self._w, sequence, '')
1533-
if funcid:
1530+
"""Unbind for this widget the event SEQUENCE.
1531+
1532+
If FUNCID is given, only unbind the function identified with FUNCID
1533+
and also delete that command.
1534+
"""
1535+
if funcid is None:
1536+
self.tk.call('bind', self._w, sequence, '')
1537+
else:
1538+
lines = self.tk.call('bind', self._w, sequence).split('\n')
1539+
prefix = f'if {{"[{funcid} '
1540+
keep = '\n'.join(line for line in lines
1541+
if not line.startswith(prefix))
1542+
if not keep.strip():
1543+
keep = ''
1544+
self.tk.call('bind', self._w, sequence, keep)
15341545
self.deletecommand(funcid)
15351546

15361547
def bind_all(self, sequence=None, func=None, add=None):
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Change the behavior of :mod:`tkinter` widget's ``unbind()`` method with two
2+
arguments. Previously, ``widget.unbind(sequence, funcid)`` destroyed the
3+
current binding for *sequence*, leaving *sequence* unbound, and deleted the
4+
*funcid* command. Now it removes only *funcid* from the binding for
5+
*sequence*, keeping other commands, and deletes the *funcid* command. It
6+
leaves *sequence* unbound only if *funcid* was the last bound command.

0 commit comments

Comments
 (0)