gh-156961: Fix tkinter.font.Font for a font name returned as a Tcl ob… · sthagen/python-cpython@62cbd34 · GitHub
Skip to content

Commit 62cbd34

Browse files
pythongh-156961: Fix tkinter.font.Font for a font name returned as a Tcl object (pythonGH-157028)
Tk can return a font name or description as a Tcl object, for example from ttk.Style().lookup("TButton", "font"), Menu.entrycget("font"), ttk.Entry.cget("font"), or the default value in the result of configure(). Such an object does not compare equal to a string, so it was not recognized as the name of an existing named font. Keep it as is, so that it is passed back to Tk, and only convert it where it is compared with a string.
1 parent c947a46 commit 62cbd34

3 files changed

Lines changed: 57 additions & 7 deletions

File tree

Lib/test/test_tkinter/test_font.py

Lines changed: 40 additions & 0 deletions

Lib/tkinter/font.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ def __init__(self, root=None, font=None, name=None, exists=False,
104104
if exists:
105105
self.name = name
106106
# confirm font exists
107-
if self.name not in tk.splitlist(tk.call("font", "names")):
107+
name = getattr(name, 'string', name) # can be a Tcl object
108+
if name not in tk.splitlist(tk.call("font", "names")):
108109
raise tkinter._tkinter.TclError(
109110
"named font %s does not already exist" % (self.name,))
110111
# if font config info supplied, apply it
@@ -123,11 +124,11 @@ def __init__(self, root=None, font=None, name=None, exists=False,
123124
self._call = tk.call
124125

125126
def __str__(self):
126-
# A wrapped description is a list or tuple, not a string; format it as
127-
# a Tcl word so it can be used as an option value (as ttk does).
128-
if isinstance(self.name, str):
129-
return self.name
130-
return tkinter._join(self.name)
127+
# A wrapped description can be a list or tuple; format it as a Tcl
128+
# word so it can be used as an option value (as ttk does).
129+
if isinstance(self.name, (list, tuple)):
130+
return tkinter._join(self.name)
131+
return str(self.name)
131132

132133
def __repr__(self):
133134
return f"<{self.__class__.__module__}.{self.__class__.__qualname__}" \
@@ -136,7 +137,13 @@ def __repr__(self):
136137
def __eq__(self, other):
137138
if not isinstance(other, Font):
138139
return NotImplemented
139-
return self.name == other.name and self._tk == other._tk
140+
name = self.name
141+
other_name = other.name
142+
if type(name) is not type(other_name):
143+
# A Tcl object does not compare equal to a string.
144+
name = getattr(name, 'string', name)
145+
other_name = getattr(other_name, 'string', other_name)
146+
return name == other_name and self._tk == other._tk
140147

141148
def __getitem__(self, key):
142149
return self.cget(key)
Lines changed: 3 additions & 0 deletions

0 commit comments

Comments
 (0)