simpledialog.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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, _get_default_root
  21. class SimpleDialog:
  22. def __init__(self, master,
  23. text='', buttons=[], default=None, cancel=None,
  24. title=None, class_=None):
  25. if class_:
  26. self.root = Toplevel(master, class_=class_)
  27. else:
  28. self.root = Toplevel(master)
  29. if title:
  30. self.root.title(title)
  31. self.root.iconname(title)
  32. _setup_dialog(self.root)
  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. master = parent
  108. if not master:
  109. master = _get_default_root('create dialog window')
  110. Toplevel.__init__(self, master)
  111. self.withdraw() # remain invisible for now
  112. # If the parent is not viewable, don't
  113. # make the child transient, or else it
  114. # would be opened withdrawn
  115. if parent is not None and parent.winfo_viewable():
  116. self.transient(parent)
  117. if title:
  118. self.title(title)
  119. _setup_dialog(self)
  120. self.parent = parent
  121. self.result = None
  122. body = Frame(self)
  123. self.initial_focus = self.body(body)
  124. body.pack(padx=5, pady=5)
  125. self.buttonbox()
  126. if not self.initial_focus:
  127. self.initial_focus = self
  128. self.protocol("WM_DELETE_WINDOW", self.cancel)
  129. if parent is not None:
  130. self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
  131. parent.winfo_rooty()+50))
  132. self.deiconify() # become visible now
  133. self.initial_focus.focus_set()
  134. # wait for window to appear on screen before calling grab_set
  135. self.wait_visibility()
  136. self.grab_set()
  137. self.wait_window(self)
  138. def destroy(self):
  139. '''Destroy the window'''
  140. self.initial_focus = None
  141. Toplevel.destroy(self)
  142. #
  143. # construction hooks
  144. def body(self, master):
  145. '''create dialog body.
  146. return widget that should have initial focus.
  147. This method should be overridden, and is called
  148. by the __init__ method.
  149. '''
  150. pass
  151. def buttonbox(self):
  152. '''add standard button box.
  153. override if you do not want the standard buttons
  154. '''
  155. box = Frame(self)
  156. w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
  157. w.pack(side=LEFT, padx=5, pady=5)
  158. w = Button(box, text="Cancel", width=10, command=self.cancel)
  159. w.pack(side=LEFT, padx=5, pady=5)
  160. self.bind("<Return>", self.ok)
  161. self.bind("<Escape>", self.cancel)
  162. box.pack()
  163. #
  164. # standard button semantics
  165. def ok(self, event=None):
  166. if not self.validate():
  167. self.initial_focus.focus_set() # put focus back
  168. return
  169. self.withdraw()
  170. self.update_idletasks()
  171. try:
  172. self.apply()
  173. finally:
  174. self.cancel()
  175. def cancel(self, event=None):
  176. # put focus back to the parent window
  177. if self.parent is not None:
  178. self.parent.focus_set()
  179. self.destroy()
  180. #
  181. # command hooks
  182. def validate(self):
  183. '''validate the data
  184. This method is called automatically to validate the data before the
  185. dialog is destroyed. By default, it always validates OK.
  186. '''
  187. return 1 # override
  188. def apply(self):
  189. '''process the data
  190. This method is called automatically to process the data, *after*
  191. the dialog is destroyed. By default, it does nothing.
  192. '''
  193. pass # override
  194. def _setup_dialog(w):
  195. if w._windowingsystem == "aqua":
  196. w.tk.call("::tk::unsupported::MacWindowStyle", "style",
  197. w, "moveableModal", "")
  198. elif w._windowingsystem == "x11":
  199. w.wm_attributes("-type", "dialog")
  200. # --------------------------------------------------------------------
  201. # convenience dialogues
  202. class _QueryDialog(Dialog):
  203. def __init__(self, title, prompt,
  204. initialvalue=None,
  205. minvalue = None, maxvalue = None,
  206. parent = None):
  207. self.prompt = prompt
  208. self.minvalue = minvalue
  209. self.maxvalue = maxvalue
  210. self.initialvalue = initialvalue
  211. Dialog.__init__(self, parent, title)
  212. def destroy(self):
  213. self.entry = None
  214. Dialog.destroy(self)
  215. def body(self, master):
  216. w = Label(master, text=self.prompt, justify=LEFT)
  217. w.grid(row=0, padx=5, sticky=W)
  218. self.entry = Entry(master, name="entry")
  219. self.entry.grid(row=1, padx=5, sticky=W+E)
  220. if self.initialvalue is not None:
  221. self.entry.insert(0, self.initialvalue)
  222. self.entry.select_range(0, END)
  223. return self.entry
  224. def validate(self):
  225. try:
  226. result = self.getresult()
  227. except ValueError:
  228. messagebox.showwarning(
  229. "Illegal value",
  230. self.errormessage + "\nPlease try again",
  231. parent = self
  232. )
  233. return 0
  234. if self.minvalue is not None and result < self.minvalue:
  235. messagebox.showwarning(
  236. "Too small",
  237. "The allowed minimum value is %s. "
  238. "Please try again." % self.minvalue,
  239. parent = self
  240. )
  241. return 0
  242. if self.maxvalue is not None and result > self.maxvalue:
  243. messagebox.showwarning(
  244. "Too large",
  245. "The allowed maximum value is %s. "
  246. "Please try again." % self.maxvalue,
  247. parent = self
  248. )
  249. return 0
  250. self.result = result
  251. return 1
  252. class _QueryInteger(_QueryDialog):
  253. errormessage = "Not an integer."
  254. def getresult(self):
  255. return self.getint(self.entry.get())
  256. def askinteger(title, prompt, **kw):
  257. '''get an integer from the user
  258. Arguments:
  259. title -- the dialog title
  260. prompt -- the label text
  261. **kw -- see SimpleDialog class
  262. Return value is an integer
  263. '''
  264. d = _QueryInteger(title, prompt, **kw)
  265. return d.result
  266. class _QueryFloat(_QueryDialog):
  267. errormessage = "Not a floating point value."
  268. def getresult(self):
  269. return self.getdouble(self.entry.get())
  270. def askfloat(title, prompt, **kw):
  271. '''get a float from the user
  272. Arguments:
  273. title -- the dialog title
  274. prompt -- the label text
  275. **kw -- see SimpleDialog class
  276. Return value is a float
  277. '''
  278. d = _QueryFloat(title, prompt, **kw)
  279. return d.result
  280. class _QueryString(_QueryDialog):
  281. def __init__(self, *args, **kw):
  282. if "show" in kw:
  283. self.__show = kw["show"]
  284. del kw["show"]
  285. else:
  286. self.__show = None
  287. _QueryDialog.__init__(self, *args, **kw)
  288. def body(self, master):
  289. entry = _QueryDialog.body(self, master)
  290. if self.__show is not None:
  291. entry.configure(show=self.__show)
  292. return entry
  293. def getresult(self):
  294. return self.entry.get()
  295. def askstring(title, prompt, **kw):
  296. '''get a string from the user
  297. Arguments:
  298. title -- the dialog title
  299. prompt -- the label text
  300. **kw -- see SimpleDialog class
  301. Return value is a string
  302. '''
  303. d = _QueryString(title, prompt, **kw)
  304. return d.result
  305. if __name__ == '__main__':
  306. def test():
  307. root = Tk()
  308. def doit(root=root):
  309. d = SimpleDialog(root,
  310. text="This is a test dialog. "
  311. "Would this have been an actual dialog, "
  312. "the buttons below would have been glowing "
  313. "in soft pink light.\n"
  314. "Do you believe this?",
  315. buttons=["Yes", "No", "Cancel"],
  316. default=0,
  317. cancel=2,
  318. title="Test Dialog")
  319. print(d.go())
  320. print(askinteger("Spam", "Egg count", initialvalue=12*12))
  321. print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1,
  322. maxvalue=100))
  323. print(askstring("Spam", "Egg label"))
  324. t = Button(root, text='Test', command=doit)
  325. t.pack()
  326. q = Button(root, text='Quit', command=t.quit)
  327. q.pack()
  328. t.mainloop()
  329. test()