blob: 3e24e28ef58cde90dafe78016ce38867a008b450 [file] [log] [blame]
Fredrik Lundhd4893982005-11-12 15:28:52 +00001# Tkinter font wrapper
Guido van Rossum3d16d3e1998-08-11 19:07:58 +00002#
Fredrik Lundhd4893982005-11-12 15:28:52 +00003# written by Fredrik Lundh, February 1998
Guido van Rossum3d16d3e1998-08-11 19:07:58 +00004#
Guido van Rossum3d16d3e1998-08-11 19:07:58 +00005
Andrew Svetlov39f00372012-04-03 09:48:07 +03006import itertools
Georg Brandl14fc4272008-05-17 18:39:55 +00007import tkinter
Guido van Rossum3d16d3e1998-08-11 19:07:58 +00008
Flavian Hautbois76b64512019-07-26 03:30:33 +02009__version__ = "0.9"
10__all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC",
11 "nametofont", "Font", "families", "names"]
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030012
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000013# weight/slant
14NORMAL = "normal"
Martin v. Löwis1ef23652003-06-14 21:40:04 +000015ROMAN = "roman"
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000016BOLD = "bold"
17ITALIC = "italic"
18
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030019
Desmond Cheong36a779e2020-12-26 05:18:06 +080020def nametofont(name, root=None):
Martin v. Löwisfe84d172004-08-18 11:06:45 +000021 """Given the name of a tk named font, returns a Font representation.
22 """
Desmond Cheong36a779e2020-12-26 05:18:06 +080023 return Font(name=name, exists=True, root=root)
Tim Petersa45cacf2004-08-20 03:47:14 +000024
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000025
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030026class Font:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000027 """Represents a named font.
28
29 Constructor options are:
30
31 font -- font specifier (name, system font, or (family, size, style)-tuple)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000032 name -- name to use for this font configuration (defaults to a unique name)
33 exists -- does a named font by this name already exist?
34 Creates a new named font if False, points to the existing font if True.
35 Raises _tkinter.TclError if the assertion is false.
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000036
Martin v. Löwisfe84d172004-08-18 11:06:45 +000037 the following are ignored if font is specified:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000038
39 family -- font 'family', e.g. Courier, Times, Helvetica
40 size -- font size in points
41 weight -- font thickness: NORMAL, BOLD
Martin v. Löwis1ef23652003-06-14 21:40:04 +000042 slant -- font slant: ROMAN, ITALIC
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000043 underline -- font underlining: false (0), true (1)
44 overstrike -- font strikeout: false (0), true (1)
Tim Petersa45cacf2004-08-20 03:47:14 +000045
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000046 """
47
Andrew Svetlov39f00372012-04-03 09:48:07 +030048 counter = itertools.count(1)
49
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000050 def _set(self, kw):
51 options = []
52 for k, v in kw.items():
53 options.append("-"+k)
54 options.append(str(v))
55 return tuple(options)
56
57 def _get(self, args):
Fred Draked038ca82000-10-23 18:31:14 +000058 options = []
59 for k in args:
60 options.append("-"+k)
61 return tuple(options)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000062
63 def _mkdict(self, args):
64 options = {}
65 for i in range(0, len(args), 2):
66 options[args[i][1:]] = args[i+1]
67 return options
68
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030069 def __init__(self, root=None, font=None, name=None, exists=False,
70 **options):
Serhiy Storchakabb70b2a2020-12-25 17:04:26 +020071 if root is None:
Serhiy Storchaka3d569fd2020-12-19 12:17:08 +020072 root = tkinter._get_default_root('use font')
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030073 tk = getattr(root, 'tk', root)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000074 if font:
75 # get actual settings corresponding to the given font
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030076 font = tk.splitlist(tk.call("font", "actual", font))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000077 else:
78 font = self._set(options)
79 if not name:
Andrew Svetlov39f00372012-04-03 09:48:07 +030080 name = "font" + str(next(self.counter))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000081 self.name = name
Martin v. Löwisfe84d172004-08-18 11:06:45 +000082
83 if exists:
84 self.delete_font = False
85 # confirm font exists
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030086 if self.name not in tk.splitlist(tk.call("font", "names")):
Georg Brandl14fc4272008-05-17 18:39:55 +000087 raise tkinter._tkinter.TclError(
88 "named font %s does not already exist" % (self.name,))
Martin v. Löwisfe84d172004-08-18 11:06:45 +000089 # if font config info supplied, apply it
90 if font:
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030091 tk.call("font", "configure", self.name, *font)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000092 else:
93 # create new font (raises TclError if the font exists)
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030094 tk.call("font", "create", self.name, *font)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000095 self.delete_font = True
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030096 self._tk = tk
97 self._split = tk.splitlist
98 self._call = tk.call
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000099
100 def __str__(self):
101 return self.name
102
Anatoliy Platonovb4d89532020-10-14 13:02:51 +0300103 def __repr__(self):
104 return f"<{self.__class__.__module__}.{self.__class__.__qualname__}" \
105 f" object {self.name!r}>"
106
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000107 def __eq__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300108 if not isinstance(other, Font):
109 return NotImplemented
Serhiy Storchaka1df56bc2020-12-29 12:56:55 +0200110 return self.name == other.name and self._tk == other._tk
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000111
112 def __getitem__(self, key):
113 return self.cget(key)
114
115 def __setitem__(self, key, value):
116 self.configure(**{key: value})
117
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000118 def __del__(self):
119 try:
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000120 if self.delete_font:
121 self._call("font", "delete", self.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000122 except Exception:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000123 pass
Tim Petersa45cacf2004-08-20 03:47:14 +0000124
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000125 def copy(self):
126 "Return a distinct copy of the current font"
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300127 return Font(self._tk, **self.actual())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000128
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300129 def actual(self, option=None, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000130 "Return actual font attributes"
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300131 args = ()
132 if displayof:
133 args = ('-displayof', displayof)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000134 if option:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300135 args = args + ('-' + option, )
136 return self._call("font", "actual", self.name, *args)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000137 else:
138 return self._mkdict(
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300139 self._split(self._call("font", "actual", self.name, *args)))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000140
141 def cget(self, option):
142 "Get font attribute"
143 return self._call("font", "config", self.name, "-"+option)
144
145 def config(self, **options):
146 "Modify font attributes"
147 if options:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000148 self._call("font", "config", self.name,
149 *self._set(options))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000150 else:
151 return self._mkdict(
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300152 self._split(self._call("font", "config", self.name)))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000153
154 configure = config
Fred Draked038ca82000-10-23 18:31:14 +0000155
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300156 def measure(self, text, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000157 "Return text width"
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300158 args = (text,)
159 if displayof:
160 args = ('-displayof', displayof, text)
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300161 return self._tk.getint(self._call("font", "measure", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000162
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300163 def metrics(self, *options, **kw):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000164 """Return font metrics.
165
166 For best performance, create a dummy widget
167 using this font before calling this method."""
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300168 args = ()
169 displayof = kw.pop('displayof', None)
170 if displayof:
171 args = ('-displayof', displayof)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000172 if options:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300173 args = args + self._get(options)
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300174 return self._tk.getint(
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300175 self._call("font", "metrics", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000176 else:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300177 res = self._split(self._call("font", "metrics", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000178 options = {}
179 for i in range(0, len(res), 2):
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300180 options[res[i][1:]] = self._tk.getint(res[i+1])
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000181 return options
182
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300183
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300184def families(root=None, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000185 "Get font families (as a tuple)"
Serhiy Storchakabb70b2a2020-12-25 17:04:26 +0200186 if root is None:
Serhiy Storchaka3d569fd2020-12-19 12:17:08 +0200187 root = tkinter._get_default_root('use font.families()')
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300188 args = ()
189 if displayof:
190 args = ('-displayof', displayof)
191 return root.tk.splitlist(root.tk.call("font", "families", *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000192
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300193
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000194def names(root=None):
195 "Get names of defined fonts (as a tuple)"
Serhiy Storchakabb70b2a2020-12-25 17:04:26 +0200196 if root is None:
Serhiy Storchaka3d569fd2020-12-19 12:17:08 +0200197 root = tkinter._get_default_root('use font.names()')
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000198 return root.tk.splitlist(root.tk.call("font", "names"))
199
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300200
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000201# --------------------------------------------------------------------
202# test stuff
Fred Draked038ca82000-10-23 18:31:14 +0000203
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000204if __name__ == "__main__":
205
Georg Brandl14fc4272008-05-17 18:39:55 +0000206 root = tkinter.Tk()
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000207
208 # create a font
209 f = Font(family="times", size=30, weight=NORMAL)
210
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000211 print(f.actual())
212 print(f.actual("family"))
213 print(f.actual("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000214
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000215 print(f.config())
216 print(f.cget("family"))
217 print(f.cget("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000218
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print(names())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000220
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print(f.measure("hello"), f.metrics("linespace"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000222
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300223 print(f.metrics(displayof=root))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000224
225 f = Font(font=("Courier", 20, "bold"))
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300226 print(f.measure("hello"), f.metrics("linespace", displayof=root))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000227
Georg Brandl14fc4272008-05-17 18:39:55 +0000228 w = tkinter.Label(root, text="Hello, world", font=f)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000229 w.pack()
230
Georg Brandl14fc4272008-05-17 18:39:55 +0000231 w = tkinter.Button(root, text="Quit!", command=root.destroy)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000232 w.pack()
233
234 fb = Font(font=w["font"]).copy()
235 fb.config(weight=BOLD)
Fred Draked038ca82000-10-23 18:31:14 +0000236
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000237 w.config(font=fb)
238
Georg Brandl14fc4272008-05-17 18:39:55 +0000239 tkinter.mainloop()