tkinter — Python interface to Tcl/Tk¶
Source code: Lib/tkinter/__init__.py
The tkinter package (“Tk interface”) is the standard Python interface to
the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix
platforms, including macOS, as well as on Windows systems.
Running python -m tkinter from the command line should open a window
demonstrating a simple Tk interface, letting you know that tkinter is
properly installed on your system, and also showing what version of Tcl/Tk is
installed, so you can read the Tcl/Tk documentation specific to that version.
See also
- TkDocs
Extensive tutorial on creating user interfaces with Tkinter. Explains key concepts, and illustrates recommended approaches using the modern API.
- Tkinter 8.5 reference: a GUI for Python
Reference documentation for Tkinter 8.5 detailing available classes, methods, and options.
Tcl/Tk Resources:
- Tk commands
Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.
- Tcl/Tk Home Page
Additional documentation, and links to Tcl/Tk core development.
Books:
- Modern Tkinter for Busy Python Developers
By Mark Roseman. (ISBN 978-1999149567)
- Python and Tkinter Programming
By Alan Moore. (ISBN 978-1788835886)
- Programming Python
By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101)
- Tcl and the Tk Toolkit (2nd edition)
By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330)
Tkinter Modules¶
Support for Tkinter is spread across several modules. Most applications will need the
main tkinter module, as well as the tkinter.ttk module, which provides
the modern themed widget set and API:
from tkinter import *
from tkinter import ttk
-
class
tkinter.Tk(screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)¶ Construct a toplevel Tk widget, which is usually the main window of an application, and initialize a Tcl interpreter for this widget. Each instance has its own associated Tcl interpreter.
The
Tkclass is typically instantiated using all default values. However, the following keyword arguments are currently recognized:- screenName
When given (as a string), sets the
DISPLAYenvironment variable. (X11 only)- baseName
Name of the profile file. By default, baseName is derived from the program name (
sys.argv[0]).- className
Name of the widget class. Used as a profile file and also as the name with which Tcl is invoked (argv0 in interp).
- useTk
If
True, initialize the Tk subsystem. Thetkinter.Tcl()function sets this toFalse.- sync
If
True, execute all X server commands synchronously, so that errors are reported immediately. Can be used for debugging. (X11 only)- use
Specifies the id of the window in which to embed the application, instead of it being created as an independent toplevel window. id must be specified in the same way as the value for the -use option for toplevel widgets (that is, it has a form like that returned by
winfo_id()).Note that on some platforms this will only work correctly if id refers to a Tk frame or toplevel that has its -container option enabled.
Tkreads and interprets profile files, named.className.tcland.baseName.tcl, into the Tcl interpreter and callsexec()on the contents of.className.pyand.baseName.py. The path for the profile files is theHOMEenvironment variable or, if that isn’t defined, thenos.curdir.-
tk¶ The Tk application object created by instantiating
Tk. This provides access to the Tcl interpreter. Each widget that is attached the same instance ofTkhas the same value for itstkattribute.
-
master¶ The widget object that contains this widget. For
Tk, the master isNonebecause it is the main window. The terms master and parent are similar and sometimes used interchangeably as argument names; however, callingwinfo_parent()returns a string of the widget name whereasmasterreturns the object. parent/child reflects the tree-like relationship while master/slave reflects the container structure.
-
tkinter.Tcl(screenName=None, baseName=None, className='Tk', useTk=False)¶ The
Tcl()function is a factory function which creates an object much like that created by theTkclass, except that it does not initialize the Tk subsystem. This is most often useful when driving the Tcl interpreter in an environment where one doesn’t want to create extraneous toplevel windows, or where one cannot (such as Unix/Linux systems without an X server). An object created by theTcl()object can have a Toplevel window created (and the Tk subsystem initialized) by calling itsloadtk()method.
The modules that provide Tk support include:
tkinterMain Tkinter module.
tkinter.colorchooserDialog to let the user choose a color.
tkinter.commondialogBase class for the dialogs defined in the other modules listed here.
tkinter.filedialogCommon dialogs to allow the user to specify a file to open or save.
tkinter.fontUtilities to help work with fonts.
tkinter.messageboxAccess to standard Tk dialog boxes.
tkinter.scrolledtextText widget with a vertical scroll bar built in.
tkinter.simpledialogBasic dialogs and convenience functions.
tkinter.ttkThemed widget set introduced in Tk 8.5, providing modern alternatives for many of the classic widgets in the main
tkintermodule.
Additional modules:
_tkinterA binary module that contains the low-level interface to Tcl/Tk. It is automatically imported by the main
tkintermodule, and should never be used directly by application programmers. It is usually a shared library (or DLL), but might in some cases be statically linked with the Python interpreter.idlelibPython’s Integrated Development and Learning Environment (IDLE). Based on
tkinter.tkinter.constantsSymbolic constants that can be used in place of strings when passing various parameters to Tkinter calls. Automatically imported by the main
tkintermodule.tkinter.dnd(experimental) Drag-and-drop support for
tkinter. This will become deprecated when it is replaced with the Tk DND.tkinter.tix(deprecated) An older third-party Tcl/Tk package that adds several new widgets. Better alternatives for most can be found in
tkinter.ttk.turtleTurtle graphics in a Tk window.
Tkinter Life Preserver¶
This section is not designed to be an exhaustive tutorial on either Tk or Tkinter. Rather, it is intended as a stop gap, providing some introductory orientation on the system.
Credits:
Tk was written by John Ousterhout while at Berkeley.
Tkinter was written by Steen Lumholt and Guido van Rossum.
This Life Preserver was written by Matt Conway at the University of Virginia.
The HTML rendering, and some liberal editing, was produced from a FrameMaker version by Ken Manheimer.
Fredrik Lundh elaborated and revised the class interface descriptions, to get them current with Tk 4.2.
Mike Clarkson converted the documentation to LaTeX, and compiled the User Interface chapter of the reference manual.
How To Use This Section¶
This section is designed in two parts: the first half (roughly) covers background material, while the second half can be taken to the keyboard as a handy reference.
When trying to answer questions of the form “how do I do blah”, it is often best
to find out how to do “blah” in straight Tk, and then convert this back into the
corresponding tkinter call. Python programmers can often guess at the
correct Python command by looking at the Tk documentation. This means that in
order to use Tkinter, you will have to know a little bit about Tk. This document
can’t fulfill that role, so the best we can do is point you to the best
documentation that exists. Here are some hints:
The authors strongly suggest getting a copy of the Tk man pages. Specifically, the man pages in the
manNdirectory are most useful. Theman3man pages describe the C interface to the Tk library and thus are not especially helpful for script writers.Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for the novice. The book is not exhaustive, and for many details it defers to the man pages.
tkinter/__init__.pyis a last resort for most, but can be a good place to go when nothing else makes sense.
A Simple Hello World Program¶
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
A (Very) Quick Look at Tcl/Tk¶
The class hierarchy looks complicated, but in actual practice, application programmers almost always refer to the classes at the very bottom of the hierarchy.
Notes: