Python Programming/Tkinter
Tkinter is a Python wrapper for Tcl/Tk providing a cross-platform GUI toolkit. On Windows, it comes bundled with Python; on other operating systems, it can be installed. The set of available widgets is smaller than in some other toolkits, but since Tkinter widgets are extensible, many of the missing compound widgets can be created using the extensibility, such as combo box and scrolling pane.
IDLE, Python's Integrated Development and Learning Environment, is written using Tkinter and is often distributed with Python. You can learn about features of Tkinter by playing around with menus and dialogs of IDLE. For instance, Options > Configure IDLE... dialog shows a broad variety of GUI elements including tabbed interface. You can learn about programming using Tkinter by studying IDLE source code, which, on Windows, is available e.g. in C:\Program Files\Python27\Lib\idlelib.
Python 3: The examples on this page are for Python 2. In Python 3, what was previously module Tkinter is tkinter, what was tkMessageBox is messagebox, etc.
Minimal example
[edit | edit source]A minimal example:
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
label = Label(frame, text="Hey there.")
label.pack()
quitButton = Button(frame, text="Quit", command=frame.quit)
quitButton.pack()
root.mainloop()
A minimal example made more compact - later references to GUI items not required:
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
Label(frame, text="Hey there.").pack()
Button(frame, text="Quit", command=frame.quit).pack()
root.mainloop()
A minimal example creating an application class derived from Frame:
from Tkinter import *
class App(Frame):
def __init__(self, master):
Frame.__init__(self)
self.label = Label(master, text="Hey there.")
self.label.pack()
self.quitButton = Button(master, text="Quit", command=self.quit)
self.quitButton.pack()
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
Message boxes
[edit | edit source]Simple message boxes can be created using tkMessageBox as follows:
import Tkinter, tkMessageBox
Tkinter.Tk().withdraw() # Workaround: Hide the window
answer = tkMessageBox.askokcancel("Confirmation", "File not saved. Discard?")
answer = tkMessageBox.askyesno("Confirmation", "Do you really want to delete the file?")
# Above, "OK" and "Yes" yield True, and "Cancel" and "No" yield False
tkMessageBox.showwarning("Warning", "Timeout has elapsed.")
tkMessageBox.showwarning("Warning", "Timeout has elapsed.", icon=tkMessageBox.ERROR)
tkMessageBox.showerror("Warning", "Timeout has elapsed.")
Links:
- The tkMessageBox dialogs module, infohost.nmt.edu
- Standard Dialogs, effbot.org
File dialog
[edit | edit source]File dialogs can be created as follows:
import Tkinter, tkFileDialog
Tkinter.Tk().withdraw() # Workaround: Hide the window
filename1 = tkFileDialog.askopenfilename()
filename2 = tkFileDialog.askopenfilename(initialdir=r"C:\Users")
filename3 = tkFileDialog.asksaveasfilename()
filename4 = tkFileDialog.asksaveasfilename(initialdir=r"C:\Users")
if filename1 <> "":
for line in open(filename1): # Dummy reading of the file
dummy = line.rstrip()
Links:
- The tkFileDialog module, infohost.nmt.edu
- File Dialogs, effbot.org
- tkFileDialog, tkinter.unpythonic.net
Radio button
[edit | edit source]A radio button can be used to create a simple choice dialog with multiple options:
from Tkinter import *
master = Tk()
choices = [("Apple", "a"), ("Orange", "o"), ("Pear", "p")]
defaultChoice = "a"
userchoice = StringVar()
userchoice.set(defaultChoice)
def cancelAction(): userchoice.set("");master.quit()
Label(master, text="Choose a fruit:").pack()
for text, key in choices:
Radiobutton(master, text=text, variable=userchoice, value=key).pack(anchor=W)
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if userchoice.get() <>"":
print userchoice.get() # "a", or "o", or "p"
else:
print "Choice canceled."
An alternative to radio button that immediately reacts to button press:
from Tkinter import *
import os
buttons = [("Users", r"C:\Users"),
("Windows", r"C:\Windows"),
("Program Files", r"C:\Program Files")]
master = Tk()
def open(filePath):
def openInner():
os.chdir(filePath) # Cross platform
#os.system('start "" "'+filePath+'') # Windows
master.quit()
return openInner
Label(master, text="Choose a fruit:").pack()
for buttonLabel, filePath in buttons:
Button(master, text=buttonLabel, command=open(filePath)).pack(anchor=W)
mainloop()
Links:
- The Radiobutton widget, infohost.nmt.edu
- The Tkinter Radiobutton Widget, effbot.org
List box
[edit | edit source]A list box can be used to create a simple multiple-choice dialog:
from Tkinter import *
master = Tk()
choices = ["Apple", "Orange", "Pear"]
canceled = BooleanVar()
def cancelAction(): canceled.set(True); master.quit()
Label(master, text="Choose a fruit:").pack()
listbox = Listbox(master, selectmode=EXTENDED) # Multiple options can be chosen
for text in choices:
listbox.insert(END, text)
listbox.pack()
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if not canceled.get():
print listbox.curselection() # A tuple of choice indices starting with 0
# The above is a tuple even if selectmode=SINGLE
if "0" in listbox.curselection(): print "Apple chosen."
if "1" in listbox.curselection(): print "Orange chosen."
if "2" in listbox.curselection(): print "Pear chosen."
else:
print "Choice canceled."
Links:
- The Listbox widget, infohost.nmt.edu
- The Tkinter Listbox Widget, effbot.org
- TKinter Listbox example (Python recipe), code.activestate.com
Checkbox
[edit | edit source]Checkbox or check button can be created as follows:
from Tkinter import *
root = Tk()
checkbuttonState = IntVar()
Checkbutton(root, text="Recursive", variable=checkbuttonState).pack()
mainloop()
print checkbuttonState.get() # 1 = checked; 0 = unchecked
Links:
- The Checkbutton widget, infohost.nmt.edu
- The Tkinter Checkbutton Widget, effbot.org
Entry
[edit | edit source]Entry widget, a single-line text input field, can be used as follows:
from Tkinter import *
root = Tk()
Label(text="Enter your first name:").pack()
entryContent = StringVar()
Entry(root, textvariable=entryContent).pack()
mainloop()
print entryContent.get()
Links:
- The Entry widget, infohost.nmt.edu
- The Tkinter Entry Widget, effbot.org
Menu
[edit | edit source]Menus can be created as follows:
from Tkinter import *
root = Tk()
def mycommand(): print "Chosen."
menubar = Menu(root)
menu1 = Menu(menubar, tearoff=0)
menu1.add_command(label="New", command=mycommand)
menu1.add_command(label="Clone", command=mycommand)
menu1.add_separator()
menu1.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Project", menu=menu1)
menu2 = Menu(menubar, tearoff=0)
menu2.add_command(label="Oval", command=mycommand)
menu2.add_command(label="Rectangle", command=mycommand)
menubar.add_cascade(label="Shapes", menu=menu2)
root.config(menu=menubar)
mainloop()
Links:
- The Menu widget, infohost.nmt.edu
- The Tkinter Menu Widget, effbot.org
LabelFrame
[edit | edit source]A frame around other elements can be created using LabelFrame widget as follows:
from Tkinter import *
root = Tk()
Label(text="Bus").pack()
frame = LabelFrame(root, text="Fruits") # text is optional
frame.pack()
Label(frame, text="Apple").pack()
Label(frame, text="Orange").pack()
mainloop()
Links:
- The LabelFrame widget, infohost.nmt.edu
- Tkinter LabelFrame Widget, effbot.org
Message
[edit | edit source]Message is like Label but ready to wrap across multiple lines. An example:
from Tkinter import *
root = Tk()
Message(text="Lazy brown fox jumped. " * 5, width=100).pack() # width is optional
mainloop()
Links:
- The Message widget, infohost.nmt.edu
- The Tkinter Message Widget, effbot.org
Option menu
[edit | edit source]Drop-down list, in Tkinter option menu, can be created as follows:
from Tkinter import *
root = Tk()
options = ["Apple", "Orange", "Pear"]
selectedOption = StringVar()
selectedOption.set("Apple") # Default
OptionMenu(root, selectedOption, *options).pack()
mainloop()
print selectedOption.get() # The text in the options list
Links:
- The OptionMenu widget, infohost.nmt.edu
- The Tkinter OptionMenu Widget, effbot.org
Text
[edit | edit source]Text widget is a more complex one, allowing editing of both plain and formatted text, including multiple fonts.
Example to be added.
Links:
- The Text widget, infohost.nmt.edu
- The Tkinter Text Widget, effbot.org
Tcl/Tk version
[edit | edit source]The Windows installer for Python 2.3 ships with Tcl/Tk 8.4.3. You can find out about the version:
import Tkinter
print Tkinter.TclVersion # Up to 8.5
print Tkinter.TkVersion # Up to 8.5
Links:
- What's new in Python 2.3, python.org
Related books
[edit | edit source]External links
[edit | edit source]- 24.1. Tkinter — Python interface to Tcl/Tk, python.org
- Tkinter 8.5 reference: a GUI for Python, infohost.nmt.edu; the same as pdf
- An Introduction to Tkinter, effbot.org
- Tkinter Summary, staff.washington.edu
- TkInter, wiki.python.org
- GUI Tk « Python, java2s.com, many examples