emayecs | 5656b2b | 2021-08-04 12:44:13 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Tim Edwards | 55f4d0e | 2020-07-05 15:41:02 -0400 | [diff] [blame] | 2 | # |
| 3 | # Dialog class for tkinter |
| 4 | |
| 5 | import os |
| 6 | import tkinter |
| 7 | from tkinter import ttk |
| 8 | |
| 9 | class Dialog(tkinter.Toplevel): |
| 10 | |
| 11 | def __init__(self, parent, message = None, title = None, seed = None, border = 'blue', **kwargs): |
| 12 | |
| 13 | tkinter.Toplevel.__init__(self, parent) |
| 14 | self.transient(parent) |
| 15 | |
| 16 | if title: |
| 17 | self.title(title) |
| 18 | |
| 19 | self.configure(background=border, padx=2, pady=2) |
| 20 | self.obox = ttk.Frame(self) |
| 21 | self.obox.pack(side = 'left', fill = 'both', expand = 'true') |
| 22 | |
| 23 | self.parent = parent |
| 24 | self.result = None |
| 25 | body = ttk.Frame(self.obox) |
| 26 | self.initial_focus = self.body(body, message, seed, **kwargs) |
| 27 | body.pack(padx = 5, pady = 5) |
| 28 | self.buttonbox() |
| 29 | self.grab_set() |
| 30 | |
| 31 | if not self.initial_focus: |
| 32 | self.initial_focus = self |
| 33 | |
| 34 | self.protocol("WM_DELETE_WINDOW", self.cancel) |
| 35 | self.geometry("+%d+%d" % (parent.winfo_rootx() + 50, |
| 36 | parent.winfo_rooty() + 50)) |
| 37 | |
| 38 | self.initial_focus.focus_set() |
| 39 | self.wait_window(self) |
| 40 | |
| 41 | # Construction hooks |
| 42 | |
| 43 | def body(self, master, **kwargs): |
| 44 | # Create dialog body. Return widget that should have |
| 45 | # initial focus. This method should be overridden |
| 46 | pass |
| 47 | |
| 48 | def buttonbox(self): |
| 49 | # Add standard button box. Override if you don't want the |
| 50 | # standard buttons |
| 51 | |
| 52 | box = ttk.Frame(self.obox) |
| 53 | |
| 54 | self.okb = ttk.Button(box, text="OK", width=10, command=self.ok, default='active') |
| 55 | self.okb.pack(side='left', padx=5, pady=5) |
| 56 | w = ttk.Button(box, text="Cancel", width=10, command=self.cancel) |
| 57 | w.pack(side='left', padx=5, pady=5) |
| 58 | |
| 59 | self.bind("<Return>", self.ok) |
| 60 | self.bind("<Escape>", self.cancel) |
| 61 | box.pack(fill='x', expand='true') |
| 62 | |
| 63 | # Standard button semantics |
| 64 | |
| 65 | def ok(self, event=None): |
| 66 | |
| 67 | if not self.validate(): |
| 68 | self.initial_focus.focus_set() # put focus back |
| 69 | return |
| 70 | |
| 71 | self.withdraw() |
| 72 | self.update_idletasks() |
| 73 | self.result = self.apply() |
| 74 | self.cancel() |
| 75 | |
| 76 | def cancel(self, event=None): |
| 77 | |
| 78 | # Put focus back to the parent window |
| 79 | self.parent.focus_set() |
| 80 | self.destroy() |
| 81 | |
| 82 | def validate(self): |
| 83 | return 1 # Override this |
| 84 | |
| 85 | def apply(self): |
| 86 | return None # Override this |