/Lib/lib-tk/tkSimpleDialog.py

http://unladen-swallow.googlecode.com/ · Python · 319 lines · 148 code · 72 blank · 99 comment · 20 complexity · 4d8bfd459327aa5565d6a2af2a179bcd MD5 · raw file

  1. #
  2. # An Introduction to Tkinter
  3. # tkSimpleDialog.py
  4. #
  5. # Copyright (c) 1997 by Fredrik Lundh
  6. #
  7. # fredrik@pythonware.com
  8. # http://www.pythonware.com
  9. #
  10. # --------------------------------------------------------------------
  11. # dialog base class
  12. '''Dialog boxes
  13. This module handles dialog boxes. It contains the following
  14. public symbols:
  15. Dialog -- a base class for dialogs
  16. askinteger -- get an integer from the user
  17. askfloat -- get a float from the user
  18. askstring -- get a string from the user
  19. '''
  20. from Tkinter import *
  21. class Dialog(Toplevel):
  22. '''Class to open dialogs.
  23. This class is intended as a base class for custom dialogs
  24. '''
  25. def __init__(self, parent, title = None):
  26. '''Initialize a dialog.
  27. Arguments:
  28. parent -- a parent window (the application window)
  29. title -- the dialog title
  30. '''
  31. Toplevel.__init__(self, parent)
  32. # If the master is not viewable, don't
  33. # make the child transient, or else it
  34. # would be opened withdrawn
  35. if parent.winfo_viewable():
  36. self.transient(parent)
  37. if title:
  38. self.title(title)
  39. self.parent = parent
  40. self.result = None
  41. body = Frame(self)
  42. self.initial_focus = self.body(body)
  43. body.pack(padx=5, pady=5)
  44. self.buttonbox()
  45. self.wait_visibility() # window needs to be visible for the grab
  46. self.grab_set()
  47. if not self.initial_focus:
  48. self.initial_focus = self
  49. self.protocol("WM_DELETE_WINDOW", self.cancel)
  50. if self.parent is not None:
  51. self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
  52. parent.winfo_rooty()+50))
  53. self.initial_focus.focus_set()
  54. self.wait_window(self)
  55. def destroy(self):
  56. '''Destroy the window'''
  57. self.initial_focus = None
  58. Toplevel.destroy(self)
  59. #
  60. # construction hooks
  61. def body(self, master):
  62. '''create dialog body.
  63. return widget that should have initial focus.
  64. This method should be overridden, and is called
  65. by the __init__ method.
  66. '''
  67. pass
  68. def buttonbox(self):
  69. '''add standard button box.
  70. override if you do not want the standard buttons
  71. '''
  72. box = Frame(self)
  73. w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
  74. w.pack(side=LEFT, padx=5, pady=5)
  75. w = Button(box, text="Cancel", width=10, command=self.cancel)
  76. w.pack(side=LEFT, padx=5, pady=5)
  77. self.bind("<Return>", self.ok)
  78. self.bind("<Escape>", self.cancel)
  79. box.pack()
  80. #
  81. # standard button semantics
  82. def ok(self, event=None):
  83. if not self.validate():
  84. self.initial_focus.focus_set() # put focus back
  85. return
  86. self.withdraw()
  87. self.update_idletasks()
  88. try:
  89. self.apply()
  90. finally:
  91. self.cancel()
  92. def cancel(self, event=None):
  93. # put focus back to the parent window
  94. if self.parent is not None:
  95. self.parent.focus_set()
  96. self.destroy()
  97. #
  98. # command hooks
  99. def validate(self):
  100. '''validate the data
  101. This method is called automatically to validate the data before the
  102. dialog is destroyed. By default, it always validates OK.
  103. '''
  104. return 1 # override
  105. def apply(self):
  106. '''process the data
  107. This method is called automatically to process the data, *after*
  108. the dialog is destroyed. By default, it does nothing.
  109. '''
  110. pass # override
  111. # --------------------------------------------------------------------
  112. # convenience dialogues
  113. class _QueryDialog(Dialog):
  114. def __init__(self, title, prompt,
  115. initialvalue=None,
  116. minvalue = None, maxvalue = None,
  117. parent = None):
  118. if not parent:
  119. import Tkinter
  120. parent = Tkinter._default_root
  121. self.prompt = prompt
  122. self.minvalue = minvalue
  123. self.maxvalue = maxvalue
  124. self.initialvalue = initialvalue
  125. Dialog.__init__(self, parent, title)
  126. def destroy(self):
  127. self.entry = None
  128. Dialog.destroy(self)
  129. def body(self, master):
  130. w = Label(master, text=self.prompt, justify=LEFT)
  131. w.grid(row=0, padx=5, sticky=W)
  132. self.entry = Entry(master, name="entry")
  133. self.entry.grid(row=1, padx=5, sticky=W+E)
  134. if self.initialvalue:
  135. self.entry.insert(0, self.initialvalue)
  136. self.entry.select_range(0, END)
  137. return self.entry
  138. def validate(self):
  139. import tkMessageBox
  140. try:
  141. result = self.getresult()
  142. except ValueError:
  143. tkMessageBox.showwarning(
  144. "Illegal value",
  145. self.errormessage + "\nPlease try again",
  146. parent = self
  147. )
  148. return 0
  149. if self.minvalue is not None and result < self.minvalue:
  150. tkMessageBox.showwarning(
  151. "Too small",
  152. "The allowed minimum value is %s. "
  153. "Please try again." % self.minvalue,
  154. parent = self
  155. )
  156. return 0
  157. if self.maxvalue is not None and result > self.maxvalue:
  158. tkMessageBox.showwarning(
  159. "Too large",
  160. "The allowed maximum value is %s. "
  161. "Please try again." % self.maxvalue,
  162. parent = self
  163. )
  164. return 0
  165. self.result = result
  166. return 1
  167. class _QueryInteger(_QueryDialog):
  168. errormessage = "Not an integer."
  169. def getresult(self):
  170. return int(self.entry.get())
  171. def askinteger(title, prompt, **kw):
  172. '''get an integer from the user
  173. Arguments:
  174. title -- the dialog title
  175. prompt -- the label text
  176. **kw -- see SimpleDialog class
  177. Return value is an integer
  178. '''
  179. d = _QueryInteger(title, prompt, **kw)
  180. return d.result
  181. class _QueryFloat(_QueryDialog):
  182. errormessage = "Not a floating point value."
  183. def getresult(self):
  184. return float(self.entry.get())
  185. def askfloat(title, prompt, **kw):
  186. '''get a float from the user
  187. Arguments:
  188. title -- the dialog title
  189. prompt -- the label text
  190. **kw -- see SimpleDialog class
  191. Return value is a float
  192. '''
  193. d = _QueryFloat(title, prompt, **kw)
  194. return d.result
  195. class _QueryString(_QueryDialog):
  196. def __init__(self, *args, **kw):
  197. if kw.has_key("show"):
  198. self.__show = kw["show"]
  199. del kw["show"]
  200. else:
  201. self.__show = None
  202. _QueryDialog.__init__(self, *args, **kw)
  203. def body(self, master):
  204. entry = _QueryDialog.body(self, master)
  205. if self.__show is not None:
  206. entry.configure(show=self.__show)
  207. return entry
  208. def getresult(self):
  209. return self.entry.get()
  210. def askstring(title, prompt, **kw):
  211. '''get a string from the user
  212. Arguments:
  213. title -- the dialog title
  214. prompt -- the label text
  215. **kw -- see SimpleDialog class
  216. Return value is a string
  217. '''
  218. d = _QueryString(title, prompt, **kw)
  219. return d.result
  220. if __name__ == "__main__":
  221. root = Tk()
  222. root.update()
  223. print askinteger("Spam", "Egg count", initialvalue=12*12)
  224. print askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)
  225. print askstring("Spam", "Egg label")