Python – Getting Started With TK

Python has a variety of widget libraries, but TK is the one included in CPython. This post shows a very basic Python program that uses TK to create an application window with a label and a button. The application closes when the user clicks on the button.

from tkinter import *

root = Tk()

Label(root, text='Click to quit => ').pack(side=LEFT, expand=YES, fill=BOTH)
Button(root, text='Quit', command=sys.exit).pack(side=LEFT, expand=YES, fill=BOTH)

root.mainloop()

The following window appears when the application is executed.
tk

Explanation

The program starts by importing the tkinter module on line 1. This module contains the widgets (or controls) that we need to create our application window. On line 3, we create a root variable and assign it to a main (or root) window by calling the Tk() function. We are now ready to start creating our controls.

Line 5 creates a Label control. The first argument in the constructor is its parent window, so we pass in root. The text argument assigns text to the label. Next, we call the pack() method on the control. In our case, we use three optional arguments. Side is used to tell the layout manager which side the control should stick too. In our case, we want to left aling our controls so we use LEFT. The expand parameter tells the label to expand with the window, while the fill control tells the control which directions it should expand or shrink (horizontal, vertical, or both).

Line 6 creates a Button that we can click on. The root is still the main window while the text is the button’s text. The command is the action the button should execute when clicked. In our case, we are telling the application to exit because we are passing the sys.exit function to the command argument. The pack() method does the same as the Label on line 5.

Finally, we want to show the window and make the program wait for events. We do this by calling root.mainloop(). Once mainloop() executes, the script will only respond to code found in event handlers, which is command=sys.exit in our case.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: