ยปCore Development>Code coverage>Lib/tkinter/simpledialog.py

Python code coverage for Lib/tkinter/simpledialog.py

#countcontent
1n/a#
2n/a# An Introduction to Tkinter
3n/a#
4n/a# Copyright (c) 1997 by Fredrik Lundh
5n/a#
6n/a# This copyright applies to Dialog, askinteger, askfloat and asktring
7n/a#
8n/a# fredrik@pythonware.com
9n/a# http://www.pythonware.com
10n/a#
11n/a"""This modules handles dialog boxes.
12n/a
13n/aIt contains the following public symbols:
14n/a
15n/aSimpleDialog -- A simple but flexible modal dialog box
16n/a
17n/aDialog -- a base class for dialogs
18n/a
19n/aaskinteger -- get an integer from the user
20n/a
21n/aaskfloat -- get a float from the user
22n/a
23n/aaskstring -- get a string from the user
24n/a"""
25n/a
26n/afrom tkinter import *
27n/afrom tkinter import messagebox
28n/a
29n/aimport tkinter # used at _QueryDialog for tkinter._default_root
30n/a
31n/aclass SimpleDialog:
32n/a
33n/a def __init__(self, master,
34n/a text='', buttons=[], default=None, cancel=None,
35n/a title=None, class_=None):
36n/a if class_:
37n/a self.root = Toplevel(master, class_=class_)
38n/a else:
39n/a self.root = Toplevel(master)
40n/a if title:
41n/a self.root.title(title)
42n/a self.root.iconname(title)
43n/a self.message = Message(self.root, text=text, aspect=400)
44n/a self.message.pack(expand=1, fill=BOTH)
45n/a self.frame = Frame(self.root)
46n/a self.frame.pack()
47n/a self.num = default
48n/a self.cancel = cancel
49n/a self.default = default
50n/a self.root.bind('<Return>', self.return_event)
51n/a for num in range(len(buttons)):
52n/a s = buttons[num]
53n/a b = Button(self.frame, text=s,
54n/a command=(lambda self=self, num=num: self.done(num)))
55n/a if num == default:
56n/a b.config(relief=RIDGE, borderwidth=8)
57n/a b.pack(side=LEFT, fill=BOTH, expand=1)
58n/a self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)
59n/a self._set_transient(master)
60n/a
61n/a def _set_transient(self, master, relx=0.5, rely=0.3):
62n/a widget = self.root
63n/a widget.withdraw() # Remain invisible while we figure out the geometry
64n/a widget.transient(master)
65n/a widget.update_idletasks() # Actualize geometry information
66n/a if master.winfo_ismapped():
67n/a m_width = master.winfo_width()
68n/a m_height = master.winfo_height()
69n/a m_x = master.winfo_rootx()
70n/a m_y = master.winfo_rooty()
71n/a else:
72n/a m_width = master.winfo_screenwidth()
73n/a m_height = master.winfo_screenheight()
74n/a m_x = m_y = 0
75n/a w_width = widget.winfo_reqwidth()
76n/a w_height = widget.winfo_reqheight()
77n/a x = m_x + (m_width - w_width) * relx
78n/a y = m_y + (m_height - w_height) * rely
79n/a if x+w_width > master.winfo_screenwidth():
80n/a x = master.winfo_screenwidth() - w_width
81n/a elif x < 0:
82n/a x = 0
83n/a if y+w_height > master.winfo_screenheight():
84n/a y = master.winfo_screenheight() - w_height
85n/a elif y < 0:
86n/a y = 0
87n/a widget.geometry("+%d+%d" % (x, y))
88n/a widget.deiconify() # Become visible at the desired location
89n/a
90n/a def go(self):
91n/a self.root.wait_visibility()
92n/a self.root.grab_set()
93n/a self.root.mainloop()
94n/a self.root.destroy()
95n/a return self.num
96n/a
97n/a def return_event(self, event):
98n/a if self.default is None:
99n/a self.root.bell()
100n/a else:
101n/a self.done(self.default)
102n/a
103n/a def wm_delete_window(self):
104n/a if self.cancel is None:
105n/a self.root.bell()
106n/a else:
107n/a self.done(self.cancel)
108n/a
109n/a def done(self, num):
110n/a self.num = num
111n/a self.root.quit()
112n/a
113n/a
114n/aclass Dialog(Toplevel):
115n/a
116n/a '''Class to open dialogs.
117n/a
118n/a This class is intended as a base class for custom dialogs
119n/a '''
120n/a
121n/a def __init__(self, parent, title = None):
122n/a
123n/a '''Initialize a dialog.
124n/a
125n/a Arguments:
126n/a
127n/a parent -- a parent window (the application window)
128n/a
129n/a title -- the dialog title
130n/a '''
131n/a Toplevel.__init__(self, parent)
132n/a
133n/a self.withdraw() # remain invisible for now
134n/a # If the master is not viewable, don't
135n/a # make the child transient, or else it
136n/a # would be opened withdrawn
137n/a if parent.winfo_viewable():
138n/a self.transient(parent)
139n/a
140n/a if title:
141n/a self.title(title)
142n/a
143n/a self.parent = parent
144n/a
145n/a self.result = None
146n/a
147n/a body = Frame(self)
148n/a self.initial_focus = self.body(body)
149n/a body.pack(padx=5, pady=5)
150n/a
151n/a self.buttonbox()
152n/a
153n/a if not self.initial_focus:
154n/a self.initial_focus = self
155n/a
156n/a self.protocol("WM_DELETE_WINDOW", self.cancel)
157n/a
158n/a if self.parent is not None:
159n/a self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
160n/a parent.winfo_rooty()+50))
161n/a
162n/a self.deiconify() # become visible now
163n/a
164n/a self.initial_focus.focus_set()
165n/a
166n/a # wait for window to appear on screen before calling grab_set
167n/a self.wait_visibility()
168n/a self.grab_set()
169n/a self.wait_window(self)
170n/a
171n/a def destroy(self):
172n/a '''Destroy the window'''
173n/a self.initial_focus = None
174n/a Toplevel.destroy(self)
175n/a
176n/a #
177n/a # construction hooks
178n/a
179n/a def body(self, master):
180n/a '''create dialog body.
181n/a
182n/a return widget that should have initial focus.
183n/a This method should be overridden, and is called
184n/a by the __init__ method.
185n/a '''
186n/a pass
187n/a
188n/a def buttonbox(self):
189n/a '''add standard button box.
190n/a
191n/a override if you do not want the standard buttons
192n/a '''
193n/a
194n/a box = Frame(self)
195n/a
196n/a w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
197n/a w.pack(side=LEFT, padx=5, pady=5)
198n/a w = Button(box, text="Cancel", width=10, command=self.cancel)
199n/a w.pack(side=LEFT, padx=5, pady=5)
200n/a
201n/a self.bind("<Return>", self.ok)
202n/a self.bind("<Escape>", self.cancel)
203n/a
204n/a box.pack()
205n/a
206n/a #
207n/a # standard button semantics
208n/a
209n/a def ok(self, event=None):
210n/a
211n/a if not self.validate():
212n/a self.initial_focus.focus_set() # put focus back
213n/a return
214n/a
215n/a self.withdraw()
216n/a self.update_idletasks()
217n/a
218n/a try:
219n/a self.apply()
220n/a finally:
221n/a self.cancel()
222n/a
223n/a def cancel(self, event=None):
224n/a
225n/a # put focus back to the parent window
226n/a if self.parent is not None:
227n/a self.parent.focus_set()
228n/a self.destroy()
229n/a
230n/a #
231n/a # command hooks
232n/a
233n/a def validate(self):
234n/a '''validate the data
235n/a
236n/a This method is called automatically to validate the data before the
237n/a dialog is destroyed. By default, it always validates OK.
238n/a '''
239n/a
240n/a return 1 # override
241n/a
242n/a def apply(self):
243n/a '''process the data
244n/a
245n/a This method is called automatically to process the data, *after*
246n/a the dialog is destroyed. By default, it does nothing.
247n/a '''
248n/a
249n/a pass # override
250n/a
251n/a
252n/a# --------------------------------------------------------------------
253n/a# convenience dialogues
254n/a
255n/aclass _QueryDialog(Dialog):
256n/a
257n/a def __init__(self, title, prompt,
258n/a initialvalue=None,
259n/a minvalue = None, maxvalue = None,
260n/a parent = None):
261n/a
262n/a if not parent:
263n/a parent = tkinter._default_root
264n/a
265n/a self.prompt = prompt
266n/a self.minvalue = minvalue
267n/a self.maxvalue = maxvalue
268n/a
269n/a self.initialvalue = initialvalue
270n/a
271n/a Dialog.__init__(self, parent, title)
272n/a
273n/a def destroy(self):
274n/a self.entry = None
275n/a Dialog.destroy(self)
276n/a
277n/a def body(self, master):
278n/a
279n/a w = Label(master, text=self.prompt, justify=LEFT)
280n/a w.grid(row=0, padx=5, sticky=W)
281n/a
282n/a self.entry = Entry(master, name="entry")
283n/a self.entry.grid(row=1, padx=5, sticky=W+E)
284n/a
285n/a if self.initialvalue is not None:
286n/a self.entry.insert(0, self.initialvalue)
287n/a self.entry.select_range(0, END)
288n/a
289n/a return self.entry
290n/a
291n/a def validate(self):
292n/a try:
293n/a result = self.getresult()
294n/a except ValueError:
295n/a messagebox.showwarning(
296n/a "Illegal value",
297n/a self.errormessage + "\nPlease try again",
298n/a parent = self
299n/a )
300n/a return 0
301n/a
302n/a if self.minvalue is not None and result < self.minvalue:
303n/a messagebox.showwarning(
304n/a "Too small",
305n/a "The allowed minimum value is %s. "
306n/a "Please try again." % self.minvalue,
307n/a parent = self
308n/a )
309n/a return 0
310n/a
311n/a if self.maxvalue is not None and result > self.maxvalue:
312n/a messagebox.showwarning(
313n/a "Too large",
314n/a "The allowed maximum value is %s. "
315n/a "Please try again." % self.maxvalue,
316n/a parent = self
317n/a )
318n/a return 0
319n/a
320n/a self.result = result
321n/a
322n/a return 1
323n/a
324n/a
325n/aclass _QueryInteger(_QueryDialog):
326n/a errormessage = "Not an integer."
327n/a def getresult(self):
328n/a return self.getint(self.entry.get())
329n/a
330n/adef askinteger(title, prompt, **kw):
331n/a '''get an integer from the user
332n/a
333n/a Arguments:
334n/a
335n/a title -- the dialog title
336n/a prompt -- the label text
337n/a **kw -- see SimpleDialog class
338n/a
339n/a Return value is an integer
340n/a '''
341n/a d = _QueryInteger(title, prompt, **kw)
342n/a return d.result
343n/a
344n/aclass _QueryFloat(_QueryDialog):
345n/a errormessage = "Not a floating point value."
346n/a def getresult(self):
347n/a return self.getdouble(self.entry.get())
348n/a
349n/adef askfloat(title, prompt, **kw):
350n/a '''get a float from the user
351n/a
352n/a Arguments:
353n/a
354n/a title -- the dialog title
355n/a prompt -- the label text
356n/a **kw -- see SimpleDialog class
357n/a
358n/a Return value is a float
359n/a '''
360n/a d = _QueryFloat(title, prompt, **kw)
361n/a return d.result
362n/a
363n/aclass _QueryString(_QueryDialog):
364n/a def __init__(self, *args, **kw):
365n/a if "show" in kw:
366n/a self.__show = kw["show"]
367n/a del kw["show"]
368n/a else:
369n/a self.__show = None
370n/a _QueryDialog.__init__(self, *args, **kw)
371n/a
372n/a def body(self, master):
373n/a entry = _QueryDialog.body(self, master)
374n/a if self.__show is not None:
375n/a entry.configure(show=self.__show)
376n/a return entry
377n/a
378n/a def getresult(self):
379n/a return self.entry.get()
380n/a
381n/adef askstring(title, prompt, **kw):
382n/a '''get a string from the user
383n/a
384n/a Arguments:
385n/a
386n/a title -- the dialog title
387n/a prompt -- the label text
388n/a **kw -- see SimpleDialog class
389n/a
390n/a Return value is a string
391n/a '''
392n/a d = _QueryString(title, prompt, **kw)
393n/a return d.result
394n/a
395n/a
396n/a
397n/aif __name__ == '__main__':
398n/a
399n/a def test():
400n/a root = Tk()
401n/a def doit(root=root):
402n/a d = SimpleDialog(root,
403n/a text="This is a test dialog. "
404n/a "Would this have been an actual dialog, "
405n/a "the buttons below would have been glowing "
406n/a "in soft pink light.\n"
407n/a "Do you believe this?",
408n/a buttons=["Yes", "No", "Cancel"],
409n/a default=0,
410n/a cancel=2,
411n/a title="Test Dialog")
412n/a print(d.go())
413n/a print(askinteger("Spam", "Egg count", initialvalue=12*12))
414n/a print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1,
415n/a maxvalue=100))
416n/a print(askstring("Spam", "Egg label"))
417n/a t = Button(root, text='Test', command=doit)
418n/a t.pack()
419n/a q = Button(root, text='Quit', command=t.quit)
420n/a q.pack()
421n/a t.mainloop()
422n/a
423n/a test()