bing.html
001| '''
001| Here’s a complete, runnable Python Tkinter example showing how to subclass tkinter.simpledialog.Dialog to create a custom modal dialog.
001| This example includes input validation, cancel handling, and returning values.
001| '''
002| import tkinter as tk
003| from tkinter import simpledialog, messagebox
004|
005|
006| class MyCustomDialog(simpledialog.Dialog):
007| """Custom dialog subclassing tkinter.simpledialog.Dialog"""
008|
009| def __init__(self, parent, title=None, initial_value=""):
010| self.initial_value = initial_value
011| self.result = None
012| super().__init__(parent, title)
013|
014| def body(self, master):
015| """Create dialog body. Return widget to focus."""
016| tk.Label(master, text="Enter your name:").grid(row=0, column=0, padx=5, pady=5)
017| self.entry = tk.Entry(master)
018| self.entry.grid(row=0, column=1, padx=5, pady=5)
019| self.entry.insert(0, self.initial_value)
020| return self.entry
021|
022| def validate(self):
023| """Validate the input before closing the dialog."""
024| name = self.entry.get().strip()
025| if not name:
026| messagebox.showerror("Invalid Input", "Name cannot be empty.")
027| return False
028| return True
029|
030| def apply(self):
031| """Process the data after validation."""
032| self.result = self.entry.get().strip()
033|
034|
035|
036| def open_dialog():
037| dialog = MyCustomDialog(root, title="Custom Name Dialog", initial_value="John Doe")
038| if dialog.result is not None:
039| messagebox.showinfo("Result", f"You entered: {dialog.result}")
040| else:
041| messagebox.showinfo("Cancelled", "Dialog was cancelled.")
042|
043|
044| if __name__ == "__main__":
045| root = tk.Tk()
046| root.title("Tkinter Custom Dialog Example")
047| root.geometry("300x150")
048|
049| tk.Button(root, text="Open Dialog", command=open_dialog).pack(pady=40)
050|
051| root.mainloop()
052|
053| '''
053| How it works:
053|
053| Subclassing
053|
053| We inherit from simpledialog.Dialog and override:
053| body(self, master) → builds the UI.
053| validate(self) → checks input before closing.
053| apply(self) → stores the result after validation.
053|
053| Modal Behavior
053|
053| The dialog is modal by default — it blocks interaction with the main window until closed.
053|
053| Cancel Handling
053|
053| If the user presses Cancel or closes the window, result remains None.
053|
053| Input Validation
053|
053| Prevents closing until valid input is entered.
053| '''
054|