simpledialog.py 11 KB

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