Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created September 7, 2011 21:12
Show Gist options
  • Save basicxman/1201747 to your computer and use it in GitHub Desktop.
Save basicxman/1201747 to your computer and use it in GitHub Desktop.

@title: Learn Tkinter Progressively @author: basicxman @tags: learning progressively tkinter python tutorial

What is Tkinter?

  • 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 fix that.

  • Let's learn progressively*.

1st Level - Survive

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()

2nd Level - Feel comfortable

3rd Level - Better. Stronger. Faster.

4th Level - Tkinter Superpowers

Annotations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment