For example, to link a button to an event method, you write code like this:
Click here to view code image
def create_widgets(self):
self.button1 = Button(self, text="Submit", command = self.display)
self.button1.grid(row=1, column=0, sticky = W)
def display(self):
print("The button was clicked in the window")
The create_widgets() method creates a single button to display in the window area. The
Button class constructor sets the command parameter to self.display, which points to the
display() method in the class.
For now, the test display() method just uses a print() statement to display a message back in
the command line, where you started the program. Now things are starting to look more like a GUI
program! Listing 18.4 shows the script1804.py code, which creates the window with the button
and event defined.
LISTING 18.4 The script1804.py Code File
Click here to view code image
#!/usr/bin/python3
from tkinter import *
class Application(Frame):
"""Build the basic window frame template"""
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.label1 = Label(self, text='Welcome to my window!')
self.label1.grid(row=0, column=0, sticky=W)
self.button1 = Button(self, text='Click me!', command=self.display)
self.button1.grid(row=1, column=0, sticky=W)
def display(self):
"""Event handler for the button"""
print('The button in the window was clicked!')
root = Tk()
root.title('Test Button events')
root.geometry('300x100')
app = Application(root)
app.mainloop()
When you run the program from the LXTerminal, the window appears separate on the desktop.
However, when you click the Click me! button, the text from the print() method still appears in
the LXTerminal window, as shown in Figure 18.3.