blob: 1ec760ee885f9875f2e3524dafa7f5d5e458b41e [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#
5# FIXME: should add 'displayof' option where relevant (actual, families,
6# measure, and metrics)
Fred Draked038ca82000-10-23 18:31:14 +00007#
Guido van Rossum3d16d3e1998-08-11 19:07:58 +00008
9__version__ = "0.9"
10
Georg Brandl14fc4272008-05-17 18:39:55 +000011import tkinter
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000012
13# 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
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 +000024class Font:
25
26 """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
47 def _set(self, kw):
48 options = []
49 for k, v in kw.items():
50 options.append("-"+k)
51 options.append(str(v))
52 return tuple(options)
53
54 def _get(self, args):
Fred Draked038ca82000-10-23 18:31:14 +000055 options = []
56 for k in args:
57 options.append("-"+k)
58 return tuple(options)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000059
60 def _mkdict(self, args):
61 options = {}
62 for i in range(0, len(args), 2):
63 options[args[i][1:]] = args[i+1]
64 return options
65
Martin v. Löwisfe84d172004-08-18 11:06:45 +000066 def __init__(self, root=None, font=None, name=None, exists=False, **options):
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000067 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +000068 root = tkinter._default_root
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000069 if font:
70 # get actual settings corresponding to the given font
71 font = root.tk.splitlist(root.tk.call("font", "actual", font))
72 else:
73 font = self._set(options)
74 if not name:
75 name = "font" + str(id(self))
76 self.name = name
Martin v. Löwisfe84d172004-08-18 11:06:45 +000077
78 if exists:
79 self.delete_font = False
80 # confirm font exists
81 if self.name not in root.tk.call("font", "names"):
Georg Brandl14fc4272008-05-17 18:39:55 +000082 raise tkinter._tkinter.TclError(
83 "named font %s does not already exist" % (self.name,))
Martin v. Löwisfe84d172004-08-18 11:06:45 +000084 # if font config info supplied, apply it
85 if font:
Martin v. Löwisfe84d172004-08-18 11:06:45 +000086 root.tk.call("font", "configure", self.name, *font)
87 else:
88 # create new font (raises TclError if the font exists)
Tim Petersa45cacf2004-08-20 03:47:14 +000089 root.tk.call("font", "create", self.name, *font)
Martin v. Löwisfe84d172004-08-18 11:06:45 +000090 self.delete_font = True
Guido van Rossum3d16d3e1998-08-11 19:07:58 +000091 # backlinks!
92 self._root = root
93 self._split = root.tk.splitlist
94 self._call = root.tk.call
95
96 def __str__(self):
97 return self.name
98
Martin v. Löwisfe84d172004-08-18 11:06:45 +000099 def __eq__(self, other):
100 return self.name == other.name and isinstance(other, Font)
101
102 def __getitem__(self, key):
103 return self.cget(key)
104
105 def __setitem__(self, key, value):
106 self.configure(**{key: value})
107
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000108 def __del__(self):
109 try:
Martin v. Löwisfe84d172004-08-18 11:06:45 +0000110 if self.delete_font:
111 self._call("font", "delete", self.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112 except (KeyboardInterrupt, SystemExit):
113 raise
114 except Exception:
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000115 pass
Tim Petersa45cacf2004-08-20 03:47:14 +0000116
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000117 def copy(self):
118 "Return a distinct copy of the current font"
Raymond Hettingerff41c482003-04-06 09:01:11 +0000119 return Font(self._root, **self.actual())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000120
121 def actual(self, option=None):
122 "Return actual font attributes"
123 if option:
124 return self._call("font", "actual", self.name, "-"+option)
125 else:
126 return self._mkdict(
127 self._split(self._call("font", "actual", self.name))
128 )
129
130 def cget(self, option):
131 "Get font attribute"
132 return self._call("font", "config", self.name, "-"+option)
133
134 def config(self, **options):
135 "Modify font attributes"
136 if options:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000137 self._call("font", "config", self.name,
138 *self._set(options))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000139 else:
140 return self._mkdict(
141 self._split(self._call("font", "config", self.name))
142 )
143
144 configure = config
Fred Draked038ca82000-10-23 18:31:14 +0000145
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000146 def measure(self, text):
147 "Return text width"
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000148 return int(self._call("font", "measure", self.name, text))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000149
150 def metrics(self, *options):
151 """Return font metrics.
152
153 For best performance, create a dummy widget
154 using this font before calling this method."""
155
156 if options:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000157 return int(
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000158 self._call("font", "metrics", self.name, self._get(options))
159 )
160 else:
161 res = self._split(self._call("font", "metrics", self.name))
162 options = {}
163 for i in range(0, len(res), 2):
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000164 options[res[i][1:]] = int(res[i+1])
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000165 return options
166
167def families(root=None):
168 "Get font families (as a tuple)"
169 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +0000170 root = tkinter._default_root
Fred Draked038ca82000-10-23 18:31:14 +0000171 return root.tk.splitlist(root.tk.call("font", "families"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000172
173def names(root=None):
174 "Get names of defined fonts (as a tuple)"
175 if not root:
Georg Brandl14fc4272008-05-17 18:39:55 +0000176 root = tkinter._default_root
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000177 return root.tk.splitlist(root.tk.call("font", "names"))
178
179# --------------------------------------------------------------------
180# test stuff
Fred Draked038ca82000-10-23 18:31:14 +0000181
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000182if __name__ == "__main__":
183
Georg Brandl14fc4272008-05-17 18:39:55 +0000184 root = tkinter.Tk()
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000185
186 # create a font
187 f = Font(family="times", size=30, weight=NORMAL)
188
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000189 print(f.actual())
190 print(f.actual("family"))
191 print(f.actual("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000192
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000193 print(f.config())
194 print(f.cget("family"))
195 print(f.cget("weight"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000196
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000197 print(names())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000198
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000199 print(f.measure("hello"), f.metrics("linespace"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000200
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000201 print(f.metrics())
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000202
203 f = Font(font=("Courier", 20, "bold"))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000204 print(f.measure("hello"), f.metrics("linespace"))
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000205
Georg Brandl14fc4272008-05-17 18:39:55 +0000206 w = tkinter.Label(root, text="Hello, world", font=f)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000207 w.pack()
208
Georg Brandl14fc4272008-05-17 18:39:55 +0000209 w = tkinter.Button(root, text="Quit!", command=root.destroy)
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000210 w.pack()
211
212 fb = Font(font=w["font"]).copy()
213 fb.config(weight=BOLD)
Fred Draked038ca82000-10-23 18:31:14 +0000214
Guido van Rossum3d16d3e1998-08-11 19:07:58 +0000215 w.config(font=fb)
216
Georg Brandl14fc4272008-05-17 18:39:55 +0000217 tkinter.mainloop()