Object orientated programming fits extremely well with GUI programming. Using OOP, we can easily make reusable GUI components. This post shows off a quit button that confirms if the user really wants to exit the application. I got the idea from Programming Python: Powerful Object-Oriented Programming. Here is my implementation of the idea followed by the explanation.
from tkinter import * from tkinter.messagebox import * class TkQuitButton(Frame): def __init__(self, master=None, auto_pack=True, # Pack the widget automatically? dialog_title='Confirm', # Title text for the askyesno dialog dialog_message='Are you sure you want to quit?', # Message for the askyesno dialog button_text='Quit', # The quit button's text quit_command=Frame.quit, # Callback command for when the user wants to quit cnf={}, **kw): super().__init__(master, cnf, **kw) # Store our fields for later user self.quit_command = quit_command self.dialog_message = dialog_message self.dialog_title = dialog_title self.quit_button = Button(self, text=button_text, command=self.quit) # Notice that self.quit_button is exposed. This can be useful for when # the client code needs to configure this frame on its own if auto_pack: self.pack_widget() # This let's us override the packing def pack_widget(self): self.pack() self.quit_button.pack(side=LEFT, expand=YES, fill=BOTH) def quit(self): # Call the askyesno dialog result = askyesno(self.dialog_title, self.dialog_message) if result: # if they quit, then execute the stored callback command self.quit_command(self) if __name__ == '__main__': TkQuitButton().mainloop()
This class extends the Frame class and packs a button into the frame. There are a few configuration properties that can be passed into the constructor. For example, we can auto_pack the widget so that it uses a default packing scheme. We can specifiy a custom title for the askyesno dialog as well as a custom message. The code even lets use customize the text of the button. We can also use a custom quit handler function should we choose to do so.
We can customize how the widget is packed in two different ways. The first way to access the quit_button property and call pack on it directly. This allows client code to change how this widget is packed into their GUIs. Alternatively, we can subclass this class and just override the pack_widget method.
The default quit implementation uses Tk’s askyesno dialog function to display a confirmation dialog to the user. It’s title and message are set to self.dialog_title and self.dialog_message properties. This allows use to customize what the user sees when the dialog is displayed. If the user presses yes, then we call the self.quit_command function which defaults to Frame.quit. Note that since self.quit is a method, we can customize this behavior by overriding it. Since we use a callback handler to exit the applicaiton, we can also customize how the application exits as well.