Let's test our basic knowledge of tkinter by creating the classic "Hello, World!" program.
First, we must import tkinter, this will vary based on version (see remarks section about "Differences between Python 2 and 3")
In Python 3 the module tkinter
has a lowercase t:
import tkinter as tk
In Python 2 the module Tkinter
has a uppercase T:
import Tkinter as tk
Using as tk
isn't strictly necessary but we will use it so the rest of this example will work the same for both version.
now that we have the tkinter module imported we can create the root of our application using the Tk
class:
root = tk.Tk()
This will act as the window for our application. (note that additional windows should be Toplevel
instances instead)
Now that we have a window, let's add text to it with a Label
label = tk.Label(root, text="Hello World!") # Create a text label
label.pack(padx=20, pady=20) # Pack it into the window
Once the application is ready we can start it (enter the main event loop) with the mainloop
method
root.mainloop()
This will open and run the application until it is stopped by the window being closed or calling exiting functions from callbacks (discussed later) such as root.destroy()
.
Putting it all together:
import tkinter as tk # Python 3.x Version
#import Tkinter as tk # Python 2.x Version
root = tk.Tk()
label = tk.Label(root, text="Hello World!") # Create a text label
label.pack(padx=20, pady=20) # Pack it into the window
root.mainloop()
And something like this should pop up: