Using Tkinter
Using Tkinter
Tkinter is a python package that describes how Python should draw its user interface. Tkinter
produces windows which are treated as objects in Python that contain various controls, known as
widgets.
The following code will produce a simple Window, with a width of 300 and height of 500:
The mainloop function at the end will start the event listener for any future widgets that you add to
the window.
import tkinter as tk
window = tk.Tk()
window.geometry("300x500")
window.mainloop()
Each widget is also an object. At the end of the object definition you will need to call the Pack
method:
import tkinter as tk
window = tk.Tk()
window.geometry("300x500")
myLabel = tk.Label(
text= "Hello, World!"
)
myLabel.pack()
window.mainloop()
Note that things do not matter what order they are defined in. The only thing that matters is the
order that they are packed in!
To make the button do something, we will attach a sub routine to it when we define it. For example:
def greenButtonPressed():
window.configure(bg='green')
greenButton = tk.Button(
text="Green",
width=25,
height=5,
command=greenButtonPressed
)
You always must have defined the sub routine at the top of the
python script so that the program can find it when you refer to it in
the creation of the button. In your reference to it, you do not need
to include the (), as you are referring by name. It is easiest to
produce a sub routine that handles each button. You can then call
subsequent functions or routines from within these.
You may have noticed that by default, Tkinter gives you your widgets in a stack, in the order that
they are packed in.
Using Pack
You can specify where you want the object to Pack to if you wish. This is good if your layout is
organised as a menu, or any other similar situation where objects are in line with one another, on
obvious places on the screen. You can use tk.LEFT, tk.RIGHT and tk.CENTER to position your widgets.
Across the page.
Absolute position might be required if your interface is generated at runtime, such as in a computer
game. You will also get much more precision using this, but it will be difficult to control.
Rather than packing your widgets, you will be placing them. You can use a combination of pack and
place in your program, but only the last applied one will work on an individual object.