@title: Learn Tkinter Progressively @author: basicxman @tags: learning progressively tkinter python tutorial
- A binding for using the Tk graphics framework in Python.
- A library which has lots of old, large, and verbose documentation
- Not so helpful to beginners.
- Let's learn progressively*.
Gotta create a window, windows have to have titles.
# Tkinter comes with a fresh installation of Python, import away!
from Tkinter import *
# Start at the root of everything.
root = Tk()
# Title that fine, fine window.
root.title("I'm a banana!")
# Enter the loop, we need this so the program will wait until the window is
# closed or the program terminated.
root.mainloop()
Shouldn't that window have a banana in it?
You're right, what good is a window without anything in it? For this, we'll need to import one more library - the Python Imaging Library. This lets us take a picture of a banana and have Tkinter be able to use it.
Make sure to install PIL though, I like to use pip.
pip install pil
Let's write up some code then...
# Gotta import the Python Imaging Library so Tkinter can read JPEGs.
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("I'm a banana!")
some_banana_photo = Image.open("im_a_banana.jpg")
the_proper_banana = ImageTk.PhotoImage(some_banana_photo)
# Didn't know a banana could be proper, but we have to call these two methods
# to open the banana jpeg and then convert it into something Tkinter finds
# useful.
# Now we just need some way to put the proper banana on the root object.
# Simple enough, let's use a Label (the standard Tkinter `widget` for
# displaying text or an image.
#
# A Label accepts an image instance with the named parameter `image` and must
# have a parent widget (our root window).
l = Label(root, image=the_proper_banana)
l.pack()
# Woah woah, what's pack? Pack is a method that can be found in Tkinter
# widgets which configures things like the size of the widget based on the
# contents of the object, and then makes it visible inside its parent.
root.mainloop()
-
- Inspired by Learn Vim Progressively