- 1). Import the Tkinter module. Importing Tkinter gives your program access to the classes, methods and functions needed to create the graphical user interface components. You can do this by using either the "import" or the "from" keyword to load the Tkinter module into your script:import Tkinterorfrom Tkinter import
- 2). Create the root widget. All components of a GUI are called widgets, and in Tk there must be a root widget to contain the rest of the widgets. Use the Tk() function to create an instance of the root widget. A program can have only one root, and it must be the first widget created in the program:root = Tk()
- 3). Label the root widget. While this is optional, it is desirable to add a meaningful label to the main window of the program. The label widget will display in the title bar of the main window. Use the pack method to automatically size the label to the widget on which it will display.t = Label(root, text="A simple Tk application")t.pack()
- 4). Add any other widgets and program statements. All other widgets created must be done between the statement that imports Tkinter and the beginning of the main event loop. For instance, to create two buttons enclosed in a frame, a frame must be instantiated and packed into the root widget. The buttons are created and packed into the frame:buttonframe = Frame(root)buttonframe.pack()messagebutton = Button(buttonframe, text="click me")cancelbutton = Button(buttonframe, text="cancel")messagebutton.pack(side=LEFT)cancelbutton.pack(side=LEFT)
- 5). Start the main event loop for the root widget using the mainloop() method. The main event loop must be started after all the other statements in the program. The event loop handles user events, like keyboard entry from the user and mouse clicks. It also monitors for updates from the windowing system and from Tk:root.mainloop()
previous post
next post