blob: 136425726ab8ce14d2963b24d1f0f84e2e4f7659 [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
6__version__ = "0.9"
7
Andrew Svetlov39f00372012-04-03 09:48:07 +03008import itertools
Georg Brandl14fc4272008-05-17 18:39:55 +00009import tkinter
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000010
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030011
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000012# weight/slant
13NORMAL = "normal"
Martin v. Löwis1ef23652003-06-14 21:40:04 +000014ROMAN = "roman"
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000015BOLD = "bold"
16ITALIC = "italic"
17
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030018
Martin v. Löwisfe84d172004-08-18 11:06:45 +000019def nametofont(name):
20 """Given the name of a tk named font, returns a Font representation.
21 """
22 return Font(name=name, exists=True)
Tim Petersa45cacf2004-08-20 03:47:14 +000023
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000024
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030025class Font:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000026 """Represents a named font.
27
28 Constructor options are:
29
30 font -- font specifier (name, system font, or (family, size, style)-tuple)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000031 name -- name to use for this font configuration (defaults to a unique name)
32 exists -- does a named font by this name already exist?
33 Creates a new named font if False, points to the existing font if True.
34 Raises _tkinter.TclError if the assertion is false.
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000035
Martin v. Löwisfe84d172004-08-18 11:06:45 +000036 the following are ignored if font is specified:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000037
38 family -- font 'family', e.g. Courier, Times, Helvetica
39 size -- font size in points
40 weight -- font thickness: NORMAL, BOLD
Martin v. Löwis1ef23652003-06-14 21:40:04 +000041 slant -- font slant: ROMAN, ITALIC
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000042 underline -- font underlining: false (0), true (1)
43 overstrike -- font strikeout: false (0), true (1)
Tim Petersa45cacf2004-08-20 03:47:14 +000044
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000045 """
46
Andrew Svetlov39f00372012-04-03 09:48:07 +030047 counter = itertools.count(1)
48
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000049 def _set(self, kw):
50 options = []
51 for k, v in kw.items():
52 options.append("-"+k)
53 options.append(str(v))
54 return tuple(options)
55
56 def _get(self, args):
Fred Draked038ca82000-10-23 18:31:14 +000057 options = []
58 for k in args:
59 options.append("-"+k)
60 return tuple(options)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000061
62 def _mkdict(self, args):
63 options = {}
64 for i in range(0, len(args), 2):
65 options[args[i][1:]] = args[i+1]
66 return options
67
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +030068 def __init__(self, root=None, font=None, name=None, exists=False,
69 **options):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000070 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +000071 root = tkinter._default_root
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030072 tk = getattr(root, 'tk', root)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000073 if font:
74 # get actual settings corresponding to the given font
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030075 font = tk.splitlist(tk.call("font", "actual", font))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000076 else:
77 font = self._set(options)
78 if not name:
Andrew Svetlov39f00372012-04-03 09:48:07 +030079 name = "font" + str(next(self.counter))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000080 self.name = name
Martin v. Löwisfe84d172004-08-18 11:06:45 +000081
82 if exists:
83 self.delete_font = False
84 # confirm font exists
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030085 if self.name not in tk.splitlist(tk.call("font", "names")):
Georg Brandl14fc4272008-05-17 18:39:55 +000086 raise tkinter._tkinter.TclError(
87 "named font %s does not already exist" % (self.name,))
Martin v. Löwisfe84d172004-08-18 11:06:45 +000088 # if font config info supplied, apply it
89 if font:
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030090 tk.call("font", "configure", self.name, *font)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000091 else:
92 # create new font (raises TclError if the font exists)
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030093 tk.call("font", "create", self.name, *font)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000094 self.delete_font = True
Serhiy Storchaka87bbf252014-08-17 15:31:59 +030095 self._tk = tk
96 self._split = tk.splitlist
97 self._call = tk.call
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000098
99 def __str__(self):
100 return self.name
101
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000102 def __eq__(self, other):
Amaury Forgeot d'Arcd61d0772010-09-17 23:27:09 +0000103 return isinstance(other, Font) and self.name == other.name
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000104
105 def __getitem__(self, key):
106 return self.cget(key)
107
108 def __setitem__(self, key, value):
109 self.configure(**{key: value})
110
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000111 def __del__(self):
112 try:
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000113 if self.delete_font:
114 self._call("font", "delete", self.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000115 except Exception:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000116 pass
Tim Petersa45cacf2004-08-20 03:47:14 +0000117
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000118 def copy(self):
119 "Return a distinct copy of the current font"
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300120 return Font(self._tk, **self.actual())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000121
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300122 def actual(self, option=None, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000123 "Return actual font attributes"
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300124 args = ()
125 if displayof:
126 args = ('-displayof', displayof)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000127 if option:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300128 args = args + ('-' + option, )
129 return self._call("font", "actual", self.name, *args)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000130 else:
131 return self._mkdict(
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300132 self._split(self._call("font", "actual", self.name, *args)))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000133
134 def cget(self, option):
135 "Get font attribute"
136 return self._call("font", "config", self.name, "-"+option)
137
138 def config(self, **options):
139 "Modify font attributes"
140 if options:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000141 self._call("font", "config", self.name,
142 *self._set(options))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000143 else:
144 return self._mkdict(
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300145 self._split(self._call("font", "config", self.name)))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000146
147 configure = config
Fred Draked038ca82000-10-23 18:31:14 +0000148
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300149 def measure(self, text, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000150 "Return text width"
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300151 args = (text,)
152 if displayof:
153 args = ('-displayof', displayof, text)
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300154 return self._tk.getint(self._call("font", "measure", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000155
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300156 def metrics(self, *options, **kw):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000157 """Return font metrics.
158
159 For best performance, create a dummy widget
160 using this font before calling this method."""
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300161 args = ()
162 displayof = kw.pop('displayof', None)
163 if displayof:
164 args = ('-displayof', displayof)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000165 if options:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300166 args = args + self._get(options)
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300167 return self._tk.getint(
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300168 self._call("font", "metrics", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000169 else:
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300170 res = self._split(self._call("font", "metrics", self.name, *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000171 options = {}
172 for i in range(0, len(res), 2):
Serhiy Storchaka4fafda72015-06-08 18:43:55 +0300173 options[res[i][1:]] = self._tk.getint(res[i+1])
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000174 return options
175
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300176
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300177def families(root=None, displayof=None):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000178 "Get font families (as a tuple)"
179 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +0000180 root = tkinter._default_root
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300181 args = ()
182 if displayof:
183 args = ('-displayof', displayof)
184 return root.tk.splitlist(root.tk.call("font", "families", *args))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000185
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300186
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000187def names(root=None):
188 "Get names of defined fonts (as a tuple)"
189 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +0000190 root = tkinter._default_root
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000191 return root.tk.splitlist(root.tk.call("font", "names"))
192
Andrew Svetlov5af3e1a2012-04-03 09:39:47 +0300193
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000194# --------------------------------------------------------------------
195# test stuff
Fred Draked038ca82000-10-23 18:31:14 +0000196
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000197if __name__ == "__main__":
198
Georg Brandl14fc4272008-05-17 18:39:55 +0000199 root = tkinter.Tk()
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000200
201 # create a font
202 f = Font(family="times", size=30, weight=NORMAL)
203
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000204 print(f.actual())
205 print(f.actual("family"))
206 print(f.actual("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000207
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print(f.config())
209 print(f.cget("family"))
210 print(f.cget("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000211
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000212 print(names())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000213
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000214 print(f.measure("hello"), f.metrics("linespace"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000215
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300216 print(f.metrics(displayof=root))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000217
218 f = Font(font=("Courier", 20, "bold"))
Andrew Svetlov20bbf542012-04-05 12:41:20 +0300219 print(f.measure("hello"), f.metrics("linespace", displayof=root))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000220
Georg Brandl14fc4272008-05-17 18:39:55 +0000221 w = tkinter.Label(root, text="Hello, world", font=f)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000222 w.pack()
223
Georg Brandl14fc4272008-05-17 18:39:55 +0000224 w = tkinter.Button(root, text="Quit!", command=root.destroy)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000225 w.pack()
226
227 fb = Font(font=w["font"]).copy()
228 fb.config(weight=BOLD)
Fred Draked038ca82000-10-23 18:31:14 +0000229
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000230 w.config(font=fb)
231
Georg Brandl14fc4272008-05-17 18:39:55 +0000232 tkinter.mainloop()