Consider the following program: from tkinter import * from tkinter import messag
ID: 3833410 • Letter: C
Question
Consider the following program: from tkinter import * from tkinter import messagebox as tkMessageBox class GUI(object): def__init__(self, parent): self.parent = parent self.parent.protocol ("WM_DELETE_WINDOW", self. Quit_handler) self. initUI() def quit_handler (self): if tkMessaqeBox.askokcancel ("Quit?", "Are you sure you want to quit?"): self.parent.quit () def initUI (self): self.parent.title ("Demo GUI") Label(self.parent, text="Enter your name") .grid(row=0, column=0, sticky=NW) self.name_str = StringVar() self.my_name = Entry (self.parent, width=30, textv ariable=self.name_str) self.my _name.grid (row=0, column=l, sticky=NW, columnspan = 20) Button (self.parent, text="Say Hello", foreground="blue", command=self.display_message) .grid(row= 1, column=1, skicky=NW) Button (self.parent, text= "Exit", foreground= "red", command=self.quit_handler) .grid(row=l, column=2) def display_message(self): tkMessageBox.showinfo("Hello", "Hello "+str(self.name_str.get())) def main(): root = T_k() myGUI = GUI (root) root.mainloop () if_name_ == " __ main __" main() Describe what each line of the main function does. Discuss the advantages of encapsulating the GUI functionality in a class. Compare the functionally of the grid and pack geometry managers.Explanation / Answer
a) root = TK() //creates an object for Tkinter
myGUI = GUI(root); // creates a GUI object using the TKinter functionality
root.mainloop() // mainloop must be called when the application is ready to run
b)
GUI programming readily lends itself to an object-oriented style, since a GUI is made up entirely of objects -- labels, buttons, scrollbars, text areas, etc. Since we're already using objects, organizing the code into larger objects makes sense. The toolbar is an object, the statusbar is an object, the navigation pane is an object, the main area is an object, each notebook tab is an object, and so on. Using objects allows to easily divide the code into modular units that are self contained, and modularizing the code is generally considered to be a best practice.
c)
grid is used to lay out widgets in a grid. Another answer says it "overlays a graph" which is a bit of a misnomer. It doesn't overlay anything, it merely arranges widgets along row and column boundaries. It is great for creating tables and other structured types of layouts.
pack lays things out along the sides of a box. It excels at doing layouts where everything is on a single row or in a single column (think rows of buttons in a toolbar or dialog box). It's also useful for very simple layouts such as a navigator on the left and a main work area on the right. It can be used to create very complex layouts but it gets tricky until you fully understand the packing algorithm.