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.

Tkinter supports a range of Tcl/Tk versions, built either with or without thread support. Tcl/Tk 8.5.12 is the minimum supported version; the official Python binary release bundles Tcl/Tk 8.6. See the source code for the _tkinter module for more information about supported versions.

Changed in version 3.11: Support for Tcl/Tk versions older than 8.5.12 was removed.

Tkinter is not a thin wrapper, but adds a fair amount of its own logic to make the experience more pythonic. This documentation will concentrate on these additions and changes, and refer to the official Tcl/Tk documentation for details that are unchanged.

Note

Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components along with a new API to use them (see tkinter.ttk). Both old and new APIs are still available. Most documentation you will find online still uses the old API and can be woefully outdated.

This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see Requirements for optional modules.

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:

Architecture

Tcl/Tk is not a single library but rather consists of a few distinct modules, each with separate functionality and its own official documentation. Python’s binary releases also ship an add-on module together with it.

Tcl

Tcl is a dynamic interpreted programming language, just like Python. Though it can be used on its own as a general-purpose programming language, it is most commonly embedded into C applications as a scripting engine or an interface to the Tk toolkit. The Tcl library has a C interface to create and manage one or more instances of a Tcl interpreter, run Tcl commands and scripts in those instances, and add custom commands implemented in either Tcl or C. Each interpreter has an event queue, and there are facilities to send events to it and process them. Unlike Python, Tcl’s execution model is designed around cooperative multitasking, and Tkinter bridges this difference (see Threading model for details).

Tk

Tk is a Tcl package implemented in C that adds custom commands to create and manipulate GUI widgets. Each Tk object embeds its own Tcl interpreter instance with Tk loaded into it. Tk’s widgets are very customizable, though at the cost of a dated appearance. Tk uses Tcl’s event queue to generate and process GUI events.

Ttk

Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better appearance on different platforms than many of the classic Tk widgets. Ttk is distributed as part of Tk, starting with Tk version 8.5. Python bindings are provided in a separate module, tkinter.ttk.

Internally, Tk and Ttk use facilities of the underlying operating system, that is, Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.

When your Python application uses a class in Tkinter, for example, to create a widget, the tkinter module first assembles a Tcl/Tk command string. It passes that Tcl command string to an internal _tkinter binary module, which then calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.

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

The modules that provide Tk support include:

tkinter

Main Tkinter module.

tkinter.colorchooser

Dialog to let the user choose a color.

tkinter.commondialog

Base class for the dialogs defined in the other modules listed here.

tkinter.filedialog

Common dialogs to allow the user to specify a file to open or save.

tkinter.font

Utilities to help work with fonts.

tkinter.messagebox

Access to standard Tk dialog boxes.

tkinter.scrolledtext

Text widget with a vertical scroll bar built in.

tkinter.simpledialog

Basic dialogs and convenience functions.

tkinter.ttk

Themed widget set introduced in Tk 8.5, providing modern alternatives for many of the classic widgets in the main tkinter module.

Additional modules:

_tkinter

A binary module that contains the low-level interface to Tcl/Tk. It is automatically imported by the main tkinter module, 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.

idlelib

Python’s Integrated Development and Learning Environment (IDLE). Based on tkinter.

tkinter.constants

Symbolic constants that can be used in place of strings when passing various parameters to Tkinter calls. Automatically imported by the main tkinter module.

tkinter.dnd

(experimental) Drag-and-drop support for tkinter. This will become deprecated when it is replaced with the Tk DND.

turtle

Turtle graphics in a Tk window.

Tkinter life preserver

This section is not designed to be an exhaustive tutorial on either Tk or Tkinter. For that, refer to one of the external resources noted earlier. Instead, this section provides a very quick orientation to what a Tkinter application looks like, identifies foundational Tk concepts, and explains how the Tkinter wrapper is structured.

The remainder of this section will help you to identify the classes, methods, and options you’ll need in your Tkinter application, and where to find more detailed documentation on them, including in the official Tcl/Tk reference manual.

A Hello World program

We’ll start by walking through a “Hello World” application in Tkinter. This isn’t the smallest one we could write, but has enough to illustrate some key concepts you’ll need to know.

from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
root.mainloop()

After the imports, the next line creates an instance of the Tk class, which initializes Tk and creates its associated Tcl interpreter. It also creates a toplevel window, known as the root window, which serves as the main window of the application.

The following line creates a frame widget, which in this case will contain a label and a button we’ll create next. The frame is fit inside the root window.

The next line creates a label widget holding a static text string. The grid() method is used to specify the relative layout (position) of the label within its containing frame widget, similar to how tables in HTML work.

A button widget is then created, and placed to the right of the label. When pressed, it will call the destroy() method of the root window.

Finally, the mainloop() method puts everything on the display, and responds to user input until the program terminates.

Important Tk concepts

Even this simple program illustrates the following key Tk concepts:

widgets

A Tkinter user interface is made up of individual widgets. Each widget is represented as a Python object, instantiated from classes like ttk.Frame, ttk.Label, and ttk.Button.

widget hierarchy

Widgets are arranged in a hierarchy. The label and button were contained within a frame, which in turn was contained within the root window. When creating each child widget, its parent widget is passed as the first argument to the widget constructor.

configuration options

Widgets have configuration options, which modify their appearance and behavior, such as the text to display in a label or button. Different classes of widgets will have different sets of options.

geometry management

Widgets aren’t automatically added to the user interface when they are created. A geometry manager like grid controls where in the user interface they are placed.

event loop

Tkinter reacts to user input, changes from your program, and even refreshes the display only when actively running an event loop. If your program isn’t running the event loop, your user interface won’t update.

Understanding how Tkinter wraps Tcl/Tk

When your application uses Tkinter’s classes and methods, internally Tkinter is assembling strings representing Tcl/Tk commands, and executing those commands in the Tcl interpreter attached to your application’s Tk instance.

Whether it’s trying to navigate reference documentation, trying to find the right method or option, adapting some existing code, or debugging your Tkinter application, there are times that it will be useful to understand what those underlying Tcl/Tk commands look like.

To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter script above.

ttk::frame .frm -padding 10
grid .frm
grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0

Tcl’s syntax is similar to many shell languages, where the first word is the command to be executed, with arguments to that command following it, separated by spaces. Without getting into too many details, notice the following:

  • The commands used to create widgets (like ttk::frame) correspond to widget classes in Tkinter.

  • Tcl widget options (like -text) correspond to keyword arguments in Tkinter.

  • Widgets are referred to by a pathname in Tcl (like .frm.btn), whereas Tkinter doesn’t use names but object references.

  • A widget’s place in the widget hierarchy is encoded in its (hierarchical) pathname, which uses a . (dot) as a path separator. The pathname for the root window is just . (dot). In Tkinter, the hierarchy is defined not by pathname but by specifying the parent widget when creating each child widget.

  • Operations which are implemented as separate commands in Tcl (like grid or destroy) are represented as methods on Tkinter widget objects. As you’ll see shortly, at other times Tcl uses what appear to be method calls on widget objects, which more closely mirror what is used in Tkinter.

How do I…? What option does…?

If you’re not sure how to do something in Tkinter, and you can’t immediately find it in the tutorial or reference documentation you’re using, there are a few strategies that can be helpful.

First, remember that the details of how individual widgets work may vary across different versions of both Tkinter and Tcl/Tk. If you’re searching documentation, make sure it corresponds to the Python and Tcl/Tk versions installed on your system.

When searching for how to use an API, it helps to know the exact name of the class, option, or method that you’re using. Introspection, either in an interactive Python shell or with print(), can help you identify what you need.

To find out what configuration options are available on any widget, call its configure() method, which returns a dictionary containing a variety of information about each object, including its default and current values. Use keys() to get just the names of each option.

btn = ttk.Button(frm, ...)
print(btn.configure().keys())

As most widgets have many configuration options in common, it can be useful to find out which are specific to a particular widget class. Comparing the list of options to that of a simpler widget, like a frame, is one way to do that.

print(set(btn.configure().keys()) - set(frm.configure().keys()))

Similarly, you can find the available methods for a widget object using the standard dir() function. If you try it, you’ll see there are over 200 common widget methods, so again identifying those specific to a widget class is helpful.

print(dir(btn))
print(set(dir(btn)) - set(dir(frm)))

Threading model

Python and Tcl/Tk have very different threading models, which tkinter tries to bridge. If you use threads, you may need to be aware of this.

A Python interpreter may have many threads associated with it. In Tcl, multiple threads can be created, but each thread has a separate Tcl interpreter instance associated with it. Threads can also create more than one interpreter instance, though each interpreter instance can be used only by the one thread that created it.

Each Tk object created by tkinter contains a Tcl interpreter. It also keeps track of which thread created that interpreter. Calls to tkinter can be made from any Python thread. Internally, if a call comes from a thread other than the one that created the Tk object, an event is posted to the interpreter’s event queue, and when executed, the result is returned to the calling Python thread.

Tcl/Tk applications are normally event-driven, meaning that after initialization, the interpreter runs an event loop (that is, Tk.mainloop) and responds to events. Because it is single-threaded, event handlers must respond quickly, otherwise they will block other events from being processed. To avoid this, any long-running computations should not run in an event handler, but are either broken into smaller pieces using timers, or run in another thread. This is different from many GUI toolkits where the GUI runs in a completely separate thread from all application code including event handlers.

If the Tcl interpreter is not running the event loop and processing events, any tkinter calls made from threads other than the one running the Tcl interpreter will fail.

A number of special cases exist:

  • Tcl/Tk libraries built without thread support are now rare: the bundled Tcl/Tk 8.6 is built with thread support, so this case only arises with some older non-threaded builds. When the library is not thread-aware, tkinter calls the library from the originating Python thread, even if this is different than the thread that created the Tcl interpreter. A global lock ensures only one call occurs at a time.

  • While tkinter allows you to create more than one instance of a Tk object (with its own interpreter), all interpreters that are part of the same thread share a common event queue, which gets ugly fast. In practice, don’t create more than one instance of Tk at a time. Otherwise, it’s best to create them in separate threads and ensure you’re running a thread-aware Tcl/Tk build.

  • Blocking event handlers are not the only way to prevent the Tcl interpreter from reentering the event loop. It is even possible to run multiple nested event loops or abandon the event loop entirely. If you’re doing anything tricky when it comes to events or threads, be aware of these possibilities.

  • There are a few select tkinter functions that presently work only when called from the thread that created the Tcl interpreter.

Handy reference

Setting options

Options control things like the color and border width of a widget. Options can be set in three ways:

At object creation time, using keyword arguments
fred = Button(self, fg="red", bg="blue")
After object creation, treating the option name like a dictionary index
fred["fg"] = "red"
fred["bg"] = "blue"
Use the config() method to update multiple attrs subsequent to object creation
fred.config(fg="red", bg="blue")

Note

The fg and bg options used here, and other options that control a widget’s appearance, belong to the classic tkinter widgets. The themed tkinter.ttk widgets recommended in the introduction do not accept them; style a themed widget through the ttk.Style class instead. The three ways of setting an option shown above apply to both widget sets.

For a complete explanation of a given option and its behavior, see the Tk man pages for the widget in question.

Note that the man pages list “STANDARD OPTIONS” and “WIDGET SPECIFIC OPTIONS” for each widget. The former is a list of options that are common to many widgets, the latter are the options that are idiosyncratic to that particular widget. The Standard Options are documented on the options(3) man page.

No distinction between standard and widget-specific options is made in this document. Some options don’t apply to some kinds of widgets. Whether a given widget responds to a particular option depends on the class of the widget; buttons have a command option, labels do not.

The options supported by a given widget are listed in that widget’s man page, or can be queried at runtime by calling the config() method without arguments, or by calling the keys() method on that widget. The return value of these calls is a dictionary whose key is the name of the option as a string (for example, 'relief') and whose values are 5-tuples.

Some options, like bg, are synonyms for common options with long names (bg is shorthand for “background”).

Index

Meaning

Example

0

option name

'relief'

1

option name for database lookup

'relief'

2

option class for database lookup

'Relief'

3

default value

'raised'

4

current value

'groove'

Example:

>>> print(fred.config())
{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

Of course, the dictionary printed will include all the options available and their values. This is meant only as an example.

Geometry management

Creating a widget does not display it. A widget appears only after it has been handed to a geometry manager, which works out its size and position inside its container and keeps the layout up to date as the container is resized or its content changes. Forgetting to call a geometry manager is a common early mistake: the widget is created, but nothing shows up.

Tk provides three geometry managers. Each is inherited by every widget, so any widget can be managed by any of them (but see the warning below about the incompatibility of grid and pack). The choice depends on the kind of layout you want.

grid

Arranges widgets in a two-dimensional table of rows and columns. It is the most flexible manager and the one to reach for by default: layouts that would otherwise need several nested frames can often be expressed as a single grid, and rows and columns can be told how to absorb extra space.

ttk.Label(frm, text="Name:").grid(column=0, row=0, sticky="w")
ttk.Entry(frm).grid(column=1, row=0)
ttk.Button(frm, text="OK").grid(column=1, row=1, sticky="e")
pack

Stacks widgets against one side of their container – "top" (the default), "bottom", "left" or "right" – and can make them fill or expand into the space that is left. It is convenient for simple arrangements, such as a single row or column of widgets or a content area framed by a toolbar and a status bar.

toolbar.pack(side="top", fill="x")
status.pack(side="bottom", fill="x")
body.pack(side="left", expand=True, fill="both")
place

Positions each widget at an explicit spot, given either as absolute screen distances or as a fraction of the container’s size. It offers the most control but the least automatic behavior, and is used the least; it suits special cases such as overlapping widgets or precise custom layouts.

background.place(x=0, y=0, relwidth=1.0, relheight=1.0)
badge.place(relx=1.0, rely=0.0, anchor="ne")

Layouts are built up by nesting: grid or pack widgets, including frames, inside a frame or toplevel. Toplevels are managed by the OS window manager. Classic and themed tkinter.ttk widgets can be managed interchangeably.

Warning

Do not apply pack() and grid() to two widgets that share the same container. The two managers negotiate sizes in incompatible ways, and the application can hang as they repeatedly resize the container against each other. To combine them, keep each manager’s widgets in a separate frame.

The full set of options accepted by each manager, with their values and defaults, is documented under Grid.grid_configure(), Pack.pack_configure() and Place.place_configure(); see also the grid(3tk), pack(3tk) and place(3tk) man pages.

Coupling widget variables

Some widgets can tie their current value directly to a program variable, so that the two stay in sync. Options such as variable, textvariable, value, onvalue and offvalue set up this connection: when the user changes the widget the variable is updated, and when the variable is set the widget redraws to match.

A widget can be linked only to a Variable object, not to an ordinary Python variable. This is not a limitation of tkinter but a consequence of how the two languages differ: the link relies on Tcl being notified every time the value changes, and Python offers no way to react when a plain variable is reassigned. A Variable sidesteps this by keeping its value inside the Tcl interpreter and exposing it through explicit get() and set() methods.

Ready-made subclasses cover the common types: StringVar, IntVar, DoubleVar and BooleanVar. Pass one as a widget’s textvariable (or variable) option, then read and update it with get() and set(); the widget tracks it with no further work on your part.

Keep a reference to the variable for as long as the widget uses it – for example by storing it as an attribute. A Variable that is garbage collected removes its underlying Tcl variable, breaking the connection to the widget (see Variable).

For example:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

# Create the application variable and give it an initial value.
contents = tk.StringVar(value="this is a variable")

# Tell the entry widget to track the variable.
entry = ttk.Entry(root, textvariable=contents)
entry.pack()

# Print the current value whenever the user presses Return.
def print_contents(event):
    print("The current entry content is:", contents.get())

entry.bind("<Return>", print_contents)

# Setting the variable from the program updates the entry through the
# same link.
def clear():
    contents.set("")

ttk.Button(root, text="Clear", command=clear).pack()

root.mainloop()

The window manager

The window manager is the part of the desktop responsible for the title bar, border and controls drawn around each top-level window, and for such things as its title, position, size and icon. Tk gives access to these through the Wm mixin, which is inherited by the Tk root window and by every Toplevel. You therefore call the window-manager methods directly on a top-level window. Each has a short name and an equivalent wm_-prefixed name, for example title() and wm_title().

These methods act on the top-level window whether its content is built from the classic widgets or the themed tkinter.ttk widgets. To reach the top-level window containing an arbitrary widget, call its winfo_toplevel() method.

For example:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("My Application")
root.geometry("640x480")
root.minsize(320, 240)

ttk.Label(root, text="Hello").pack(padx=20, pady=20)

root.mainloop()

See Wm for the full set of window-manager methods.

Tk option data types

Many widget options documented in the reference accept values of a small number of common types, described here.

anchor

Legal values are points of the compass: "n", "ne", "e", "se", "s", "sw", "w", "nw", and also "center".

bitmap

There are ten built-in, named bitmaps: 'error', 'gray12', 'gray25', 'gray50', 'gray75', 'hourglass', 'info', 'questhead', 'question', 'warning'. To specify an X bitmap filename, give the full path to the file, preceded with an @, as in "@/usr/contrib/bitmap/gumby.bit".

boolean

You can pass integers 0 or 1 or the strings "yes" or "no".

callback

This is any Python function that takes no arguments. For example:

def print_it():
    print("hi there")
fred["command"] = print_it
color

Colors can be given as the names of X colors in the rgb.txt file, or as strings representing RGB values in 4 bit: "#RGB", 8 bit: "#RRGGBB", 12 bit: "#RRRGGGBBB", or 16 bit: "#RRRRGGGGBBBB" ranges, where R,G,B here represent any legal hex digit. See the colors(3tk) man page for the list of named colors.

cursor

The name of the mouse cursor to display while the pointer is over the widget. Tk provides a portable set of cursor names available on all platforms (for example "arrow", "watch", "cross", or "hand2"); the standard X cursor names from cursorfont.h may also be used, without the XC_ prefix (so XC_hand2 becomes "hand2"). The full list of names, including the platform-specific ones, is given in the cursors(3tk) manual page. You can also specify a bitmap and mask file of your own. On Windows a cursor file (.cur or .ani) may be used directly, giving its path preceded with an @, as in "@C:/cursors/bart.ani".

distance

Screen distances can be specified in either pixels or absolute distances. Pixels are given as numbers and absolute distances as strings, with the trailing character denoting units: c for centimetres, i for inches, m for millimetres, p for printer’s points. For example, 3.5 inches is expressed as "3.5i".

font

Tk uses a font description such as {courier 10 bold}; in tkinter this is most naturally passed as a tuple of (family, size, *styles) (or as the equivalent string "Courier 10 bold"). Font sizes with positive numbers are measured in points; sizes with negative numbers are measured in pixels.

geometry

This is a string of the form widthxheight, where width and height are measured in pixels for most widgets (in characters for widgets displaying text). For example: fred["geometry"] = "200x100".

justify

Legal values are the strings: "left", "center", and "right".

region

This is a string with four space-delimited elements, each of which is a legal distance (see above). For example: "2 3 4 5" and "3i 2i 4.5i 2i" and "3c 2c 4c 10.43c" are all legal regions.

relief

Determines what the border style of a widget will be. Legal values are: "raised", "sunken", "flat", "groove", "ridge", and "solid".

scrollcommand

This is almost always the set() method of some scrollbar widget, but can be any widget method that takes a single argument.

wrap

Must be one of: "none", "char", or "word".

Bindings and events

The bind method from the widget command allows you to watch for certain events and to have a callback function trigger when that event type occurs. The form of the bind method is:

def bind(self, sequence, func, add=''):

where:

sequence

is a string that denotes the target kind of event. Physical events use the <modifier-modifier-type-detail> form (for example "<Enter>" or "<Control-Button-1>"); application-defined virtual events use double angle brackets, as in "<<Paste>>". (See the bind(3tk) man page for details.)

func

is a Python function, taking one argument, to be invoked when the event occurs. An Event instance will be passed as the argument. (Functions deployed this way are commonly known as callbacks.)

add

is optional, either '' or '+'. Passing an empty string denotes that this binding is to replace any other bindings that this event is associated with. Passing a '+' means that this function is to be added to the list of functions bound to this event type.

For example:

def turn_red(self, event):
    event.widget["activeforeground"] = "red"

self.button.bind("<Enter>", self.turn_red)

Notice how the widget field of the event is being accessed in the turn_red() callback. This field contains the widget that caught the X event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages.

Tk

Tkinter Event Field

Tk

Tkinter Event Field

%f

focus

%A

char

%h

height

%E

send_event

%k

keycode

%K

keysym

%s

state

%N

keysym_num

%t

time

%T

type

%w

width

%W

widget

%x

x

%X

x_root

%y

y

%Y

y_root

%#

serial

%b

num

%d

detail

%D

delta

The add parameter above only affects the bindings you make yourself. Every widget also inherits class bindings that implement its standard behavior – for example a Text widget binds Control-t to transpose two characters. These are described in the bindings section of the widget’s Tk man page (such as text(3tk) or entry(3tk)).

Class bindings are processed separately from your own, so binding an event yourself does not replace the default; both run. To suppress an unwanted default binding, bind the event on the widget and return the string "break" from your callback.

The index parameter

A number of widgets require “index” parameters to be passed. These are used to point at a specific place in a Text widget, or to particular characters in an Entry widget, or to particular menu items in a Menu widget.

Entry widget indexes (index, view index, etc.)

Entry widgets have methods and options that refer to character positions in the text being displayed. Anytime an index is needed, you may pass in:

  • an integer which refers to the numeric position of a character, counted from the beginning of the text, starting with 0;

  • the string "anchor", which refers to the anchor point of the selection, set with the widget’s selection methods;

  • the string "end", which refers to the position just after the last character;

  • the string "insert", which refers to the character just after the insertion cursor;

  • the strings "sel.first" and "sel.last", which refer to the first character in the selection and the position just after the last (it is an error to use these if there is no selection);

  • a string consisting of @ followed by an integer, as in "@6", where the integer is interpreted as an x pixel coordinate in the entry’s coordinate system, selecting the character spanning that point.

Text widget indexes

The index notation for Text widgets is very rich and is best described in the Tk man pages.

Menu indexes (menu.invoke(), menu.entryconfig(), etc.)

Some options and methods for menus manipulate specific menu entries. Anytime a menu index is needed for an option or a parameter, you may pass in:

  • an integer which refers to the numeric position of the entry in the widget, counted from the top, starting with 0;

  • the string "active", which refers to the menu position that is currently under the cursor;

  • the string "last" which refers to the last menu item;

  • a string consisting of @ followed by an integer, as in "@6", where the integer is interpreted as a y pixel coordinate in the menu’s coordinate system;

  • the string "none", which indicates no menu entry at all, most often used with menu.activate() to deactivate all entries, and finally,

  • a text string that is pattern matched against the label of the menu entry, as scanned from the top of the menu to the bottom. Note that this index type is considered after all the others, which means that matches for menu items labelled last, active, or none may be interpreted as the above literals, instead.

Images

Images of different formats can be created through the corresponding subclass of tkinter.Image:

  • BitmapImage for images in XBM format.

  • PhotoImage for images in PGM, PPM, GIF and PNG formats. The latter is supported starting with Tk 8.6.

Either type of image is created through either the file or the data option (other options are available as well).

Changed in version 3.13: Added the PhotoImage method copy_replace() to copy a region from one image to other image, possibly with pixel zooming and/or subsampling. Add from_coords parameter to PhotoImage methods copy(), zoom() and subsample(). Add zoom and subsample parameters to PhotoImage method copy().

The image object can then be used wherever an image option is supported by some widget (for example, labels, buttons, menus). In these cases, Tk will not keep a reference to the image. When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used.

See also

The Pillow package adds support for formats such as BMP, JPEG, TIFF, and WebP, among others.

Reference

This section documents the classes, methods, functions and constants of the tkinter module. Most of them wrap Tcl/Tk commands; consult the official Tcl/Tk manual pages for the full list of widget options and further details.

exception tkinter.TclError

The exception raised when a call into the Tcl interpreter fails, for example when a widget is given an unknown option or an invalid value.

Base and mixin classes

class tkinter.Misc

The Misc class is a mix-in inherited by Tk and, through BaseWidget, by every widget. It provides the large set of methods common to all Tk objects: querying window information, managing event bindings and the event loop, controlling the keyboard focus and pointer grabs, accessing the selection, clipboard and option database, and assorted utility and introspection services. Because they are inherited, these methods are available on every widget and on the Tk application object, and are documented here once rather than repeated for each widget.

cget(key)

Return the current value of the configuration option named key for this widget, as a string. The expression widget[key] is equivalent and may be used instead.

configure(cnf=None, **kw)

Query or modify the configuration options of the widget. With no arguments, return a dictionary mapping every available option name to a tuple describing it (its name, X resource name, X resource class, default value and current value). If a single option name is given as a string, return the tuple for just that option. If one or more keyword arguments are given, or a dictionary is passed as cnf, set each named option to the corresponding value; the expression widget[key] = value sets a single option in the same way.

config() is an alias of configure().

keys()

Return a list of the names of all configuration options of this widget.

getboolean(s)

Interpret the string s as a Tcl boolean and return the corresponding bool. Tcl accepts values such as '1', '0', 'yes', 'no', 'true' and 'false'. Raise ValueError if s is not a valid boolean.

getdouble(s)

Interpret the string s as a Tcl floating-point number and return it as a float. Raise ValueError if s is not a valid number.

Added in version 3.5.

getint(s)

Interpret the string s as a Tcl integer and return it as an int. Raise ValueError if s is not a valid integer.

getvar(name)

Return the value of the Tcl global variable named name.

setvar(name, value)

Set the Tcl global variable named name to value.

The getvar() and setvar() methods give direct access to Tcl variables. In most code you will instead use a Variable subclass such as StringVar or IntVar, which wraps a Tcl variable and converts its value to and from a Python type.

register(func, subst=None, needcleanup=1)

Register the Python callable func as a Tcl command and return the name of the new command as a string. Whenever Tcl invokes that command, func is called; if subst is given, it is applied to the command’s arguments first. This is the mechanism used internally to turn Python callbacks into the command names passed to Tk options such as command. Unless needcleanup is false, the command is deleted automatically when the widget is destroyed.

Changed in version 3.13: The arguments passed to func are no longer converted to strings.

deletecommand(name)

Delete the Tcl command named name, such as one previously returned by register().

nametowidget(name)

Return the widget instance corresponding to the Tk pathname name.

send(interp, cmd, *args)

Send the Tcl command cmd, with the given args, to the Tcl interpreter registered under the name interp, and return its result. This is not available on all platforms.

destroy()

Destroy this widget and all of its descendant widgets, and delete the Tcl commands associated with them.

tkraise(aboveThis=None)

Raise this widget in the stacking order so that it is drawn on top of its siblings. If aboveThis is given, the widget is moved to be just above it in the stacking order instead.

lift() is an alias of tkraise().

lower(belowThis=None)

Lower this widget in the stacking order so that it is drawn beneath its siblings. If belowThis is given, the widget is moved to be just below it in the stacking order instead.

tkraise()/lift() and lower() are overridden by the Canvas widget, where they restack canvas items instead.

image_names()

Return the names of all images that currently exist in the Tcl interpreter.

This is overridden by the Text widget, where image_names() returns the names of its embedded images instead.

image_types()

Return the available image types, such as 'photo' and 'bitmap'.

grid_anchor(anchor=None)

Set the anchor that controls where the grid is placed inside this container when the container is larger than the grid and no row or column has a non-zero weight. anchor is one of the usual anchor strings, such as 'nw' (the default) or 'center'. Called with no argument, this method has no effect.

anchor() is an alias of grid_anchor().

Added in version 3.3.

grid_bbox(column=None, row=None, col2=None, row2=None)

Return the bounding box, in pixels, of a region of the grid laid out in this container, as a 4-tuple (xoffset, yoffset, width, height). With no arguments the bounding box of the whole grid is returned. If column and row are given, the box spans from the cell at row and column 0 to that cell; if col2 and row2 are also given, it spans from the cell (column, row) to the cell (col2, row2).

bbox() is an alias of grid_bbox(), except on Canvas, Listbox, Spinbox, Text, ttk.Entry and ttk.Treeview, which provide their own bbox() method.

grid_columnconfigure(index, cnf={}, **kw)

Query or set the properties of the column (or columns) index of the grid managed by this container. index may be a column number; when setting options it may also be a list of column numbers, the string 'all' to affect every column, or a child widget whose occupied columns are affected. The supported options are:

minsize

The column’s minimum size, in pixels.

weight

An integer setting how much of any extra space is apportioned to the column. A weight of 0 keeps the column at its requested size, and a column of weight two grows twice as fast as a column of weight one.

uniform

The name of a uniform group. Columns sharing a non-empty group name are kept in sizes that are strictly proportional to their weights.

pad

Extra space, in pixels, added to the largest widget in the column when computing the column’s size.

With a single option name, return that option’s value; with no options, return a dictionary of all of them.

columnconfigure() is an alias of grid_columnconfigure().

grid_rowconfigure(index, cnf={}, **kw)

Query or set the properties of the row (or rows) index of the grid managed by this container. index is interpreted as for grid_columnconfigure(), and the supported options (minsize, weight, uniform and pad) are the same, applied to a row instead of a column.

rowconfigure() is an alias of grid_rowconfigure().

grid_location(x, y)

Return the (column, row) of the grid cell that contains the pixel at position (x, y), given in pixels relative to this container. For locations above or to the left of the grid, -1 is returned for the corresponding coordinate.

grid_propagate()
grid_propagate(flag)

Enable or disable geometry propagation for this container when it manages its children with the grid geometry manager. When flag is true, the container resizes itself to fit the requested sizes of its children; when it is false, its size is left under your control. Called with no argument, return the current setting as a boolean.

grid_size()

Return the size of the grid managed by this container as a (columns, rows) tuple.

size() is an alias of grid_size(), except on the Listbox widget, which provides its own size() method.

grid_slaves(row=None, column=None)

Return a list of the child widgets managed in this container’s grid, most recently managed first. If row or column is given, only the children in that row or column are returned.

pack_propagate()
pack_propagate(flag)

Enable or disable geometry propagation for this container when it manages its children with the pack geometry manager. When flag is true, the container resizes itself to fit the requested sizes of its children; when it is false, its size is left under your control. Called with no argument, return the current setting as a boolean.

propagate() is an alias of pack_propagate().

pack_slaves()

Return a list of the child widgets managed by this container with the pack geometry manager, in packing order.

slaves() is an alias of pack_slaves().

place_slaves()

Return a list of the child widgets managed by this container with the place geometry manager.

bind(sequence=None, func=None, add=None)

Bind the event pattern sequence on this widget to the callable func.

sequence is an event pattern, such as '<Button-1>' (a mouse click) or '<KeyPress-a>', optionally a concatenation of several such patterns that must occur shortly after one another. When the event occurs, func is called with an Event instance describing it as its only argument; if func returns the string 'break', no further bindings for the event are invoked.

If add is true, func is added to any functions already bound to sequence; otherwise it replaces them. The binding applies only to this widget.

bind() returns a string identifier (a funcid) that can later be passed to unbind() to remove the binding without leaking the associated Tcl command.

If func is omitted, return the binding currently associated with sequence; if sequence is also omitted, return a list of all the sequences for which bindings exist on this widget.

bind_class(className, sequence=None, func=None, add=None)

Like bind(), but bind func to the binding tag className rather than to a single widget, so that the binding applies to every widget having that tag. className is usually the name of a widget class, such as 'Button', in which case the binding affects all widgets of that class. The set of binding tags for a widget can be inspected and changed with bindtags().

The remaining arguments and the return value are as for bind().

bind_all(sequence=None, func=None, add=None)

Like bind(), but bind func to the special binding tag 'all', so that the binding applies to every widget in the application.

The remaining arguments and the return value are as for bind().

unbind(sequence, funcid=None)

Remove bindings for the event pattern sequence on this widget.

If funcid is given, only the function identified by it (a value returned from a previous call to bind()) is removed, and its associated Tcl command is deleted. Otherwise all bindings for sequence are destroyed, leaving it unbound.

Changed in version 3.13: If funcid is given, only that callback is unbound; other callbacks bound to sequence are kept.

unbind_class(className, sequence)

Remove all bindings for the event pattern sequence from the binding tag className. See bind_class().

unbind_all(sequence)

Remove all bindings for the event pattern sequence from the special binding tag 'all'. See bind_all().

bindtags(tagList=None)

If tagList is omitted, return a tuple of the binding tags associated with this widget. When an event occurs in a widget, it is applied to each of the widget’s binding tags in order, and for each tag the most specific matching binding is executed. By default a widget has four binding tags: its own pathname, its widget class, the pathname of its nearest toplevel ancestor, and 'all', in that order.

If tagList is given, it must be a sequence of strings; the widget’s binding tags are set to its elements, which determines the order in which bindings are evaluated.

The methods with the event_ prefix define virtual events and generate events programmatically.

event_add(virtual, *sequences)

Associate the virtual event virtual, whose name has the form '<<Paste>>', with each of the physical event patterns given by sequences, so that the virtual event triggers whenever any of them occurs. If virtual is already defined, the new sequences are added to its existing ones.

event_delete(virtual, *sequences)

Remove each of sequences from those associated with the virtual event virtual. Sequences that are not currently associated with virtual are ignored. If no sequences are given, all physical event sequences are removed, so that virtual no longer triggers.

event_generate(sequence, **kw)

Generate the event sequence on this widget and arrange for it to be processed just as if it had come from the window system. sequence must be a single event pattern, such as '<Button-1>' or '<<Paste>>', not a concatenation of several. Keyword arguments specify additional fields of the event, for example x and y for the pointer position, or when to control when the event is processed; refer to the Tk event manual page for the full list.

event_info(virtual=None)

If virtual is omitted, return a tuple of all the virtual events that are currently defined. If virtual is given, return a tuple of the physical event sequences currently associated with it, or an empty tuple if it is not defined.

The methods with the after prefix schedule callbacks to run after a delay or when the application is idle.

after(ms, func=None, *args, **kw)

Schedule the callable func to be called after ms milliseconds, with args and kw passed to it as positional and keyword arguments. Return an identifier that can be passed to after_cancel() to cancel the call.

If func is omitted, sleep for ms milliseconds instead, processing no events during that time, and return None.

Changed in version 3.10: func can now be any callable object, not only a function.

Changed in version 3.14: Keyword arguments are now passed to func.

after_cancel(id)

Cancel a callback previously scheduled with after() or after_idle(). id must be an identifier returned by one of those methods; passing a value that is not such an identifier raises ValueError. If the callback has already run or been cancelled, this has no effect.

Changed in version 3.7: Passing None (or any false value) as id now raises ValueError.

after_idle(func, *args, **kw)

Schedule the callable func to be called, with args and kw passed to it, when the Tk main loop next becomes idle, that is, when it has no other events to process. Return an identifier that can be passed to after_cancel() to cancel the call.

Changed in version 3.14: Keyword arguments are now passed to func.

after_info(id=None)

If id is omitted, return a tuple of the identifiers of all callbacks currently scheduled with after() and after_idle() for this interpreter.

If id is given, it must identify a callback that has not yet run or been cancelled, and the return value is a tuple (script, type), where script refers to the function to be called and type is either 'idle' or 'timer'. A TclError is raised if id does not exist.

Added in version 3.13.

mainloop(n=0)

Enter the Tk event loop, which processes events until all windows are destroyed. This is normally called once, on the root window, to run the application.

quit()

Quit the Tcl interpreter, causing mainloop() to return.

update()

Enter the event loop until all pending events, including idle callbacks, have been processed. This brings the display up to date and handles any events that are already queued, then returns.

update_idletasks()

Enter the event loop until all pending idle callbacks have been called. This updates the display of windows, for example after geometry changes, but does not process events caused by the user.

wait_variable(name)

Wait until the Tcl variable name is modified, continuing to process events in the meantime so that the application stays responsive. name is usually a Variable instance, such as an IntVar or StringVar.

waitvar() is an alias of wait_variable().

wait_window(window=None)

Wait until window is destroyed, continuing to process events in the meantime. If window is omitted, this widget is used. This is typically used to wait for the user to finish interacting with a dialog box.

wait_visibility(window=None)

Wait until the visibility state of window changes, for example when it first appears on the screen, continuing to process events in the meantime. If window is omitted, this widget is used. This is typically used to wait for a newly created window to become visible before acting on it.

The methods with the focus_ prefix manage the keyboard focus.

focus()

Direct the keyboard input focus for this widget’s display to this widget. If the application does not currently have the input focus on this widget’s display, the widget is remembered as the focus window for its top level, and the focus will be redirected to it the next time the window manager gives the focus to the top level. focus() is an alias of focus_set(), except on the Canvas and ttk.Treeview widgets, which provide their own focus() method.

focus_force()

Direct the keyboard input focus to this widget even if the application does not currently have the input focus for the widget’s display. This method should be used sparingly, if at all; normally an application should wait for the window manager to give it the focus rather than claiming it.

focus_get()

Return the widget that currently has the keyboard focus in the application, or None if no widget in the application has the focus. Use focus_displayof() to work correctly with several displays.

focus_displayof()

Return the widget that currently has the keyboard focus on the display where this widget is located, or None if no widget in the application has the focus on that display.

focus_lastfor()

Return the most recent widget to have had the keyboard focus among all the widgets in the same top level as this widget; this is the widget that will receive the focus the next time the window manager gives the focus to the top level. If no widget in that top level has ever had the focus, or if the most recent focus widget has been deleted, the top level itself is returned.

tk_focusFollowsMouse()

Reconfigure Tk to use an implicit focus model in which the focus is set to a widget whenever the mouse pointer enters it. This cannot easily be disabled once enabled.

tk_focusNext()

Return the next widget after this one in the keyboard traversal order, or None if there is none. The traversal order goes first to the next child, then recursively to the children of that child, and then to the next sibling higher in the stacking order. A widget is skipped if its takefocus option is set to 0. This method is used in the default bindings for the Tab key.

tk_focusPrev()

Return the previous widget before this one in the keyboard traversal order, or None if there is none. See tk_focusNext() for how the order is defined. This method is used in the default bindings for the Shift-Tab key.

The methods with the grab_ prefix set and query the input grab, which directs all input events to a single widget.

grab_set()

Set a local grab on this widget. A grab confines pointer events to this widget and its descendants: while the pointer is outside the widget’s subtree, button presses and releases and pointer motion are reported to the grab widget, and windows outside the subtree become insensitive until the grab is released. A local grab affects only the grabbing application. Any grab previously set by this application on the widget’s display is automatically released. Setting a grab is the usual way to make a dialog modal: while the grab is in effect the user cannot interact with the other windows of the application.

grab_set_global()

Set a global grab on this widget. A global grab is like the local grab set by grab_set(), but it locks out all other applications on the screen, so that only this widget’s subtree is sensitive to pointer events, and it also grabs the keyboard. Use with caution: it is easy to render a display unusable with a global grab, since other applications stop receiving events until it is released.

grab_release()

Release the grab on this widget if there is one; otherwise do nothing.

grab_current()

Return the widget that currently holds the grab in this application for this widget’s display, or None if there is no such widget.

grab_status()

Return None if no grab is currently set on this widget, "local" if a local grab is set, or "global" if a global grab is set.

The methods with the selection_ prefix retrieve and manage the X selection.

selection_clear(**kw)

Clear the X selection, so that no window owns it anymore. The selection to clear is given by the keyword argument selection, an atom name such as 'PRIMARY' or 'CLIPBOARD'; it defaults to PRIMARY. The displayof keyword argument names a widget that determines the display on which to operate, and defaults to this widget.

This is overridden by the Entry, Listbox and Spinbox widgets, where selection_clear() clears the widget’s own selection instead.

selection_get(**kw)

Return the contents of the current X selection. The keyword argument selection names the selection and defaults to PRIMARY. The keyword argument type specifies the form in which the data is to be returned (the desired conversion target), an atom name such as 'STRING' or 'FILE_NAME'; it defaults to STRING, except on X11, where UTF8_STRING is tried first and STRING is used as a fallback. The displayof keyword argument names a widget that determines the display from which to retrieve the selection, and defaults to this widget.

selection_handle(command, **kw)

Register command as a handler to supply the X selection owned by this widget when another application requests it. When the selection is retrieved, command is called with two arguments, the starting character offset and the maximum number of characters to return, and must return at most that many characters of the selection starting at that offset; for very long selections it is called repeatedly with increasing offsets. The keyword argument selection names the selection (default PRIMARY) and the keyword argument type gives the form of the selection that the handler supplies (such as 'STRING' or 'FILE_NAME', default STRING).

selection_own(**kw)

Make this widget the owner of the X selection on its display. The previous owner, if any, is notified that it has lost the selection. The keyword argument selection names the selection and defaults to PRIMARY.

selection_own_get(**kw)

Return the widget in this application that owns the X selection on the display containing this widget, or None if no widget in this application owns the selection. The keyword argument selection names the selection and defaults to PRIMARY. The displayof keyword argument names a widget that determines the display to query, and defaults to this widget.

The methods with the clipboard_ prefix manage the clipboard.

clipboard_append(string, **kw)

Append string to the Tk clipboard and claim ownership of the clipboard on this widget’s display. Before appending, the clipboard should be emptied with clipboard_clear(); all appends should be completed before returning to the event loop so that the clipboard is updated atomically. The keyword argument type specifies the form of the data, an atom name such as 'STRING' or 'FILE_NAME' (default STRING), and the keyword argument format specifies the representation used to transmit it (default STRING). The displayof keyword argument names a widget that determines the target display, and defaults to this widget. The contents can be retrieved with clipboard_get() or selection_get().

clipboard_clear(**kw)

Claim ownership of the clipboard on this widget’s display and remove any previous contents. The displayof keyword argument names a widget that determines the target display, and defaults to this widget.

clipboard_get(**kw)

Retrieve data from the clipboard on this widget’s display. The keyword argument type specifies the form in which the data is to be returned, an atom name such as 'STRING' or 'FILE_NAME'; it defaults to STRING, except on X11, where UTF8_STRING is tried first and STRING is used as a fallback. The displayof keyword argument names a widget that determines the display, and defaults to the root window of the application. This is equivalent to selection_get(selection='CLIPBOARD').

The methods with the option_ prefix query and modify the Tk option database.

option_add(pattern, value, priority=None)

Add an option to the Tk option database that associates value with pattern. pattern consists of names and/or classes separated by asterisks or dots, in the usual X format. priority is an integer between 0 and 100, or one of the symbolic names 'widgetDefault' (20), 'startupFile' (40), 'userDefault' (60), or 'interactive' (80); it defaults to interactive.

option_clear()

Clear the Tk option database. Default options from the RESOURCE_MANAGER property or the .Xdefaults file are reloaded automatically the next time an option is added to or removed from the database.

option_get(name, className)

Return the value of the option matching this widget under name and className from the Tk option database, or an empty string if there is no matching entry. When several entries match, the one with the highest priority is returned, and among entries of equal priority the most recently added one.

option_readfile(fileName, priority=None)

Read the file named fileName, which should have the standard format for an X resource database such as .Xdefaults, and add all the options it specifies to the Tk option database. priority is interpreted as for option_add() and defaults to interactive.

bell(displayof=0)

Ring the bell on the display for this widget, using the display’s current bell-related settings, and reset the screen saver for the screen. If displayof is given as a widget, the bell is rung on that widget’s display instead.

tk_setPalette(background, /)
tk_setPalette(*args, **kw)

Set a new color scheme for all Tk widget elements. Existing widgets are updated and the option database is changed so that future widgets use the new colors. A single color argument is taken as the normal background color, from which a complete palette is computed. Alternatively, the arguments may be given as keyword name/value pairs naming individual options in the option database. The recognized option names are activeBackground, activeForeground, background, disabledForeground, foreground, highlightBackground, highlightColor, insertBackground, selectColor, selectBackground, selectForeground, and troughColor; reasonable defaults are computed for any that are not specified.

tk_bisque()

Restore the application’s colors to the light brown (bisque) color scheme used in Tk 3.6 and earlier versions. Provided for backward compatibility.

tk_strictMotif(boolean=None)

Query or set whether Tk’s look and feel should strictly adhere to Motif. A true boolean value enables strict Motif compliance (for example, no color change when the mouse passes over a slider). Return the resulting setting.

The methods with the busy_ prefix manage the busy state of a window, which shows a busy cursor and ignores user input.

tk_busy_hold(**kw)

Make this widget appear busy. A transparent window is placed in front of the widget, so that it and all of its descendants in the widget hierarchy are blocked from pointer events and display a busy cursor. Normally update() should be called immediately afterwards to ensure that the hold operation is in effect before the application starts its processing.

The only supported configuration option is cursor, the cursor to be displayed while the widget is busy; it may have any of the values accepted by configure().

busy_hold(), busy() and tk_busy() are aliases of tk_busy_hold().

Added in version 3.13.

tk_busy_configure(cnf=None, **kw)

Query or modify the configuration options of the busy window. The widget must have been previously made busy by tk_busy_hold(). With no arguments, return a dictionary describing all of the available options; if cnf is the name of an option, return a tuple describing that one option. Otherwise set the given options to the given values. Options may have any of the values accepted by tk_busy_hold().

The option database is referenced through the widget name or class. For example, if a Frame widget named frame is to be made busy, the busy cursor can be specified for it by either of the calls:

w.option_add('*frame.busyCursor', 'gumby')
w.option_add('*Frame.BusyCursor', 'gumby')

busy_configure(), busy_config() and tk_busy_config() are aliases of tk_busy_configure().

Added in version 3.13.

tk_busy_cget(option)

Return the current value of the busy configuration option. The widget must have been previously made busy by tk_busy_hold(), and option may have any of the values accepted by that method.

busy_cget() is an alias of tk_busy_cget().

Added in version 3.13.

tk_busy_forget()

Make this widget no longer busy, releasing the resources (including the transparent window) allocated when it was made busy. User events will again be received by the widget. These resources are also released when the widget is destroyed.

busy_forget() is an alias of tk_busy_forget().

Added in version 3.13.

tk_busy_status()

Return True if the widget is currently busy, False otherwise.

busy_status() is an alias of tk_busy_status().

Added in version 3.13.

tk_busy_current(pattern=None)

Return a list of widgets that are currently busy. If pattern is given, only busy widgets whose path names match the pattern are returned.

busy_current() is an alias of tk_busy_current().

Added in version 3.13.

The methods with the winfo_ prefix retrieve information about windows managed by Tk.

winfo_atom(name, displayof=0)

Return the integer identifier for the atom whose name is name, creating a new atom if none exists. If displayof is given, the atom is looked up on the display of that window; otherwise it is looked up on the display of the application’s main window.

winfo_atomname(id, displayof=0)

Return the textual name for the atom whose integer identifier is id. This is the inverse of winfo_atom(). If displayof is given, the identifier is looked up on the display of that window; otherwise it is looked up on the display of the application’s main window.

winfo_cells()

Return the number of cells in the colormap for the widget.

winfo_children()

Return a list containing the widgets that are children of the widget, in stacking order from lowest to highest. Toplevel windows are returned as children of their logical parents.

winfo_class()

Return the class name of the widget.

winfo_colormapfull()

Return True if the colormap for the widget is known to be full, False otherwise.

winfo_containing(rootX, rootY, displayof=0)

Return the widget containing the point given by rootX and rootY, or None if no window in this application contains the point. The coordinates are in screen units in the coordinate system of the root window. If displayof is given, the coordinates refer to the screen containing that window; otherwise they refer to the screen of the application’s main window.

winfo_depth()

Return the depth of the widget, that is, the number of bits per pixel.

winfo_exists()

Return true if the widget exists, false otherwise.

winfo_fpixels(number)

Return a floating-point value giving the number of pixels in the widget corresponding to the screen distance number (for example, "2.0c" or "1i"). The result may be fractional; for a rounded integer value use winfo_pixels().

winfo_geometry()

Return the geometry of the widget, in the form widthxheight+x+y. All dimensions are in pixels. An offset can be negative; see geometry().

winfo_height()

Return the height of the widget in pixels. When a window is first created its height is 1 pixel; it is eventually changed by a geometry manager. See also winfo_reqheight().

winfo_id()

Return a low-level platform-specific identifier for the widget. On Unix this is the X window identifier, and on Windows it is the window handle.

winfo_interps(displayof=0)

Return a tuple of the names of all Tcl interpreters currently registered for a particular display. If displayof is given, the return value refers to the display of that window; otherwise it refers to the display of the application’s main window.

winfo_ismapped()

Return true if the widget is currently mapped, false otherwise.

winfo_manager()

Return the name of the geometry manager currently responsible for the widget, or an empty string if it is not managed by any geometry manager.

winfo_name()

Return the widget’s name within its parent, as opposed to its full path name.

winfo_parent()

Return the path name of the widget’s parent, or an empty string if the widget is the main window of the application.

winfo_pathname(id, displayof=0)

Return the path name of the window whose identifier is id. If displayof is given, the identifier is looked up on the display of that window; otherwise it is looked up on the display of the application’s main window.

winfo_pixels(number)

Return the number of pixels in the widget corresponding to the screen distance number (for example, "2.0c" or "1i"). The result is rounded to the nearest integer; for a fractional result use winfo_fpixels().

winfo_pointerx()

Return the pointer’s x coordinate, in pixels, relative to the screen’s root window (or virtual root, if one is in use). Return -1 if the pointer is not on the same screen as the widget.

winfo_pointerxy()

Return the pointer’s coordinates as an (x, y) tuple, in pixels, relative to the screen’s root window (or virtual root, if one is in use). Both coordinates are -1 if the pointer is not on the same screen as the widget.

winfo_pointery()

Return the pointer’s y coordinate, in pixels, relative to the screen’s root window (or virtual root, if one is in use). Return -1 if the pointer is not on the same screen as the widget.

winfo_reqheight()

Return the widget’s requested height in pixels. This is the value used by the widget’s geometry manager to compute its geometry.

winfo_reqwidth()

Return the widget’s requested width in pixels. This is the value used by the widget’s geometry manager to compute its geometry.

winfo_rgb(color)

Return an (r, g, b) tuple of the red, green, and blue intensities, in the range 0 to 65535, that correspond to color in the widget. color may be specified in any of the forms acceptable for a color option.

winfo_rootx()

Return the x coordinate, in the root window of the screen, of the upper-left corner of the widget’s border (or of the widget itself if it has no border).

winfo_rooty()

Return the y coordinate, in the root window of the screen, of the upper-left corner of the widget’s border (or of the widget itself if it has no border).

winfo_screen()

Return the name of the screen associated with the widget, in the form displayName.screenIndex.

winfo_screencells()

Return the number of cells in the default colormap for the widget’s screen.

winfo_screendepth()

Return the depth of the root window of the widget’s screen, that is, the number of bits per pixel.

winfo_screenheight()

Return the height of the widget’s screen in pixels.

winfo_screenmmheight()

Return the height of the widget’s screen in millimeters.

winfo_screenmmwidth()

Return the width of the widget’s screen in millimeters.

winfo_screenvisual()

Return the default visual class for the widget’s screen, one of "directcolor", "grayscale", "pseudocolor", "staticcolor", "staticgray", or "truecolor".

winfo_screenwidth()

Return the width of the widget’s screen in pixels.

winfo_server()

Return a string containing information about the server for the widget’s display. The exact format of this string may vary from platform to platform.

winfo_toplevel()

Return the top-of-hierarchy window containing the widget. In standard Tk this is always a Toplevel widget.

winfo_viewable()

Return true if the widget and all of its ancestors up through the nearest toplevel window are mapped, false otherwise.

winfo_visual()

Return the visual class for the widget, one of "directcolor", "grayscale", "pseudocolor", "staticcolor", "staticgray", or "truecolor".

winfo_visualid()

Return the X identifier for the visual for the widget.

winfo_visualsavailable(includeids=False)

Return a list describing the visuals available for the widget’s screen. Each item consists of a visual class (see winfo_visual()) followed by an integer depth. If includeids is true, the X identifier for the visual is also included.

winfo_vrootheight()

Return the height of the virtual root window associated with the widget if there is one; otherwise return the height of the widget’s screen.

winfo_vrootwidth()

Return the width of the virtual root window associated with the widget if there is one; otherwise return the width of the widget’s screen.

winfo_vrootx()

Return the x offset of the virtual root window associated with the widget, relative to the root window of its screen. This is normally zero or negative, and is 0 if there is no virtual root window.

winfo_vrooty()

Return the y offset of the virtual root window associated with the widget, relative to the root window of its screen. This is normally zero or negative, and is 0 if there is no virtual root window.

winfo_width()

Return the width of the widget in pixels. When a window is first created its width is 1 pixel; it is eventually changed by a geometry manager. See also winfo_reqwidth().

winfo_x()

Return the x coordinate, in the widget’s parent, of the upper-left corner of the widget’s border (or of the widget itself if it has no border).

winfo_y()

Return the y coordinate, in the widget’s parent, of the upper-left corner of the widget’s border (or of the widget itself if it has no border).

info_patchlevel()

Return the Tcl/Tk patch level as a named tuple with the same five fields as sys.version_info: major, minor, micro, releaselevel and serial. releaselevel is 'alpha', 'beta' or 'final'. Converting it to a string gives the version in the usual Tcl/Tk notation, for example '9.0.3' for a final release or '9.1b2' for a pre-release.

Added in version 3.11.

class tkinter.Wm

The Wm mixin provides access to the window manager, allowing an application to control such things as the title, geometry and icon of a top-level window, the way it is resized, and how it responds to window manager protocols. It is mixed into Tk and Toplevel, so its methods are available on every top-level window. Each method has two equivalent spellings: a short name and a wm_-prefixed name (for example, title() and wm_title()). See also The window manager.

aspect(minNumer=None, minDenom=None, maxNumer=None, maxDenom=None)

Constrain the aspect ratio (the ratio of width to height) of the window. If all four arguments are given, the window manager keeps the ratio between minNumer/minDenom and maxNumer/maxDenom; passing empty strings removes any existing restriction. With no arguments, return a tuple of the four current values, or None if no aspect restriction is in effect. wm_aspect() is an alias of aspect().

attributes(*args, return_python_dict=False, **kwargs)

Query or set platform-specific attributes of the window. With no arguments, return the platform-specific flags and their values; pass return_python_dict as true to get them as a dictionary. A single option name such as 'alpha' returns the value of that option, and options are set using keyword arguments (alpha=0.5).

The available attributes differ by platform. All platforms support:

alpha

The window’s opacity, from 0.0 (fully transparent) to 1.0 (opaque). Where transparency is unsupported the value stays at 1.0.

appearance

Whether the window is rendered in dark mode on Windows and macOS: 'auto', 'light' or 'dark' (this has no effect on X11).

fullscreen

Whether the window takes up the entire screen and has no borders.

topmost

Whether the window is displayed above all other windows.

Windows additionally supports:

disabled

Whether the window is in a disabled state.

toolwindow

Whether the window uses the tool window style.

transparentcolor

The color that is made fully transparent, or an empty string for none.

macOS additionally supports:

class

Whether the underlying Aqua window is an nswindow or an nspanel; this can only be set before the window is created.

modified

The modification state shown by the window’s close button and proxy icon.

notify

Whether the application’s dock icon bounces to request attention.

stylemask

The style mask of the underlying Aqua window, given as a list of bit names such as titled or resizable.

tabbingid

The identifier of the tab group that the window belongs to.

tabbingmode

Whether the window may be opened as a tab: 'auto', 'preferred' or 'disallowed'.

titlepath

The path of the file represented by the window’s proxy icon.

transparent

Whether the content area is transparent and the window shadow is turned off.

X11 additionally supports:

type

The window type, or a list of types in order of preference, that the window manager should use to interpret the window, such as 'dialog' or 'splash'.

zoomed

Whether the window is maximized.

Note

Tk 8.6 added the type attribute, and Tk 9.0 added the appearance, class, stylemask, tabbingid and tabbingmode attributes.

On X11 changes are applied asynchronously, so a queried value may not yet reflect the most recent request. wm_attributes() is an alias of attributes().

Changed in version 3.13: A single attribute may now be queried by name without the leading -, and attributes may be set using keyword arguments. The return_python_dict parameter was added.

Deprecated since version 3.13: Setting an attribute by passing the option name (with a leading -) and its value as two positional arguments, as in w.attributes('-alpha', 0.5), is deprecated; use keyword arguments instead.

client(name=None)

Store name, which should be the name of the host on which the application is running, in the window’s WM_CLIENT_MACHINE property for use by the window or session manager. An empty string deletes the property. With no argument, return the last name set, or an empty string. wm_client() is an alias of client().

colormapwindows(*wlist)

Manipulate the WM_COLORMAP_WINDOWS property, which tells the window manager about windows that have private colormaps. If wlist is given, overwrite the property with those windows (their order is a priority order for installing colormaps). With no arguments, return the list of windows currently named in the property. wm_colormapwindows() is an alias of colormapwindows().

command(value=None)

Store value in the window’s WM_COMMAND property for use by the window or session manager; it should be a list giving the words of the command used to invoke the application. An empty string deletes the property. With no argument, return the last value set, or an empty string. wm_command() is an alias of command().

deiconify()

Display the window in normal (non-iconified) form by mapping it. If the window has never been mapped, this ensures it appears de-iconified when it is first mapped. On Windows the window is also raised and given the focus. wm_deiconify() is an alias of deiconify().

focusmodel(model=None)

Set or query the focus model for the window. model is either 'active' (the window claims the input focus for itself or its descendants, even when the focus is in another application) or 'passive' (the window relies on the window manager to give it the focus). With no argument, return the current model. The default is 'passive', which is what the focus() command assumes. wm_focusmodel() is an alias of focusmodel().

forget(window)

Unmap window from the screen so that it is no longer managed by the window manager. A Toplevel is then treated like a Frame, although its -menu configuration is remembered and the menu reappears if the widget is managed again. wm_forget() is an alias of forget().

Not to be confused with Pack.forget().

Added in version 3.3.

frame()

Return the platform-specific window identifier for the outermost decorative frame containing the window, if the window manager has reparented it into such a frame; otherwise return the identifier of the window itself. wm_frame() is an alias of frame().

geometry(newGeometry=None)

Set or query the geometry of the window. newGeometry has the form =widthxheight+x+y, where any of =, widthxheight and the +x+y position may be omitted. width and height are in pixels (or grid units for a gridded window); a position preceded by + is measured from the left or top edge of the screen and one preceded by - from the right or bottom edge. An offset can be negative, as in '200x100+-9+-8', when the window edge is positioned beyond the corresponding screen edge. An empty string cancels any user-specified geometry, letting the window revert to its natural size. With no argument, return the current geometry as a string of the form '200x200+10+10'. wm_geometry() is an alias of geometry().

grid(baseWidth=None, baseHeight=None, widthInc=None, heightInc=None)

Manage the window as a gridded window and define the relationship between grid units and pixels. baseWidth and baseHeight are the numbers of grid units for the window’s internally requested size, and widthInc and heightInc are the pixel sizes of a horizontal and vertical grid unit. Empty strings turn off gridded management. With no arguments, return a tuple of the four current values, or None if the window is not gridded. wm_grid() is an alias of grid().

Not to be confused with the grid geometry manager Grid.grid().

group(pathName=None)

Set or query the leader of a group of related windows. pathName gives the path name of the group leader; the window manager may, for example, unmap all windows in the group when the leader is iconified. An empty string removes the window from any group. With no argument, return the path name of the current group leader, or an empty string. wm_group() is an alias of group().

iconbitmap(bitmap=None, default=None)

Set or query the bitmap used by the window manager for the window’s icon. bitmap names a bitmap in one of the standard forms accepted by Tk; an empty string cancels the current icon bitmap. With no argument, return the name of the current icon bitmap, or an empty string. On Windows the default argument names an icon (for example an .ico file) applied to all top-level windows that have no icon of their own. wm_iconbitmap() is an alias of iconbitmap().

iconify()

Iconify the window. If the window has not yet been mapped for the first time, arrange for it to appear in the iconified state when it is eventually mapped. wm_iconify() is an alias of iconify().

iconmask(bitmap=None)

Set or query the bitmap used as a mask for the icon (see iconbitmap()). Where the mask is zero no icon is displayed; where it is one, the corresponding bits of the icon bitmap are shown. An empty string cancels the current mask. With no argument, return the name of the current icon mask, or an empty string. wm_iconmask() is an alias of iconmask().

iconname(newName=None)

Set or query the name displayed by the window manager inside the window’s icon. With no argument, return the current icon name, or an empty string if none has been set (in which case the window manager normally displays the window’s title). wm_iconname() is an alias of iconname().

iconphoto(default=False, *images)

Set the titlebar icon for the window from one or more PhotoImage objects given in images. Several images of different sizes (for example 16x16 and 32x32) may be supplied so that the window manager can choose an appropriate one. The image data is taken as a snapshot at the time of the call; later changes to the images are not reflected. If default is true, the icon is also applied to all top-level windows created in the future. On macOS only the first image is used. wm_iconphoto() is an alias of iconphoto().

Added in version 3.3.

iconposition(x=None, y=None)

Set or query a hint to the window manager about where the window’s icon should be positioned. Empty strings cancel an existing hint. With no arguments, return a tuple of the two current values, or None if no hint is in effect. wm_iconposition() is an alias of iconposition().

iconwindow(pathName=None)

Set or query the window used as the icon for the window. When the window is iconified, pathName is mapped to serve as its icon and unmapped again when it is de-iconified. An empty string cancels the association. With no argument, return the path name of the current icon window, or an empty string. Not all window managers support icon windows, and the concept is meaningless on non-X11 platforms. wm_iconwindow() is an alias of iconwindow().

manage(widget)

Make widget a stand-alone top-level window, decorated by the window manager with a title bar and so on. Only Frame, LabelFrame and Toplevel widgets may be used (the tkinter.ttk versions are not accepted); passing any other widget type raises an error. wm_manage() is an alias of manage().

Added in version 3.3.

maxsize(width=None, height=None)

Set or query the maximum permissible dimensions of the window, in pixels (or grid units for a gridded window). The window manager restricts the window to be no larger than width and height. With no arguments, return a tuple of the current maximum width and height. The maximum size defaults to the size of the screen. wm_maxsize() is an alias of maxsize().

minsize(width=None, height=None)

Set or query the minimum permissible dimensions of the window, in pixels (or grid units for a gridded window). The window manager restricts the window to be no smaller than width and height. With no arguments, return a tuple of the current minimum width and height. The minimum size defaults to one pixel in each dimension. wm_minsize() is an alias of minsize().

overrideredirect(boolean=None)

Set or query the override-redirect flag for the window. When this flag is set, the window is ignored by the window manager: it is not reparented into a decorative frame and the user cannot manipulate it through the usual window manager controls. With no argument, return a boolean indicating whether the flag is set, or None if it has not been set. The flag is reliably honored only when the window is first mapped or remapped from the withdrawn state. wm_overrideredirect() is an alias of overrideredirect().

positionfrom(who=None)

Set or query the source of the window’s current position. who is either 'program' or 'user' and indicates whether the position was requested by the program or by the user; an empty string cancels the current source. With no argument, return the current source, or an empty string if none has been set. Tk automatically sets the source to 'user' when geometry() is called, unless it has been set explicitly to 'program'. wm_positionfrom() is an alias of positionfrom().

protocol(name=None, func=None)

Register func as the handler for the window manager protocol name, an atom such as 'WM_DELETE_WINDOW', 'WM_SAVE_YOURSELF' or 'WM_TAKE_FOCUS'; func is then called whenever the window manager sends a message of that protocol. Tk installs a default WM_DELETE_WINDOW handler that destroys the window, which this method can replace. If func is an empty string, the handler is removed. With only name, return the name of its registered handler command, or an empty string if none is set (the default WM_DELETE_WINDOW handler is not reported); with no arguments, return a tuple of the protocols that currently have handlers. wm_protocol() is an alias of protocol().

resizable(width=None, height=None)

Control whether the user may interactively resize the window. width and height are boolean values that determine whether the window’s width and height may be changed. With no arguments, return a tuple of two 0/1 values indicating whether each dimension is currently resizable. By default a window is resizable in both dimensions. wm_resizable() is an alias of resizable().

sizefrom(who=None)

Set or query the source of the window’s current size. who is either 'program' or 'user' and indicates whether the size was requested by the program or by the user; an empty string cancels the current source. With no argument, return the current source, or an empty string if none has been set. wm_sizefrom() is an alias of sizefrom().

state(newstate=None)

Set or query the state of the window. With no argument, return the current state: one of 'normal', 'iconic', 'withdrawn', 'icon' or, on Windows and macOS only, 'zoomed'. 'iconic' refers to a window that has been iconified, while 'icon' refers to a window serving as the icon for another window (see iconwindow()); the 'icon' state cannot be set. wm_state() is an alias of state().

Not to be confused with ttk.Widget.state.

title(string=None)

Set or query the title for the window, which the window manager should display in the window’s title bar. With no argument, return the current title. The title defaults to the window’s name. wm_title() is an alias of title().

transient(master=None)

Mark the window as a transient window (such as a pull-down menu or dialog) working on behalf of master, the path name of another top-level window. An empty string clears the transient status. With no argument, return the path name of the current master, or an empty string. A transient window mirrors state changes in its master and may be decorated differently by the window manager; it is an error to make a window a transient of itself. wm_transient() is an alias of transient().

withdraw()

Withdraw the window from the screen, unmapping it and causing the window manager to forget about it. If the window has never been mapped, it is instead mapped in the withdrawn state. It is sometimes necessary to withdraw a window and then re-map it (for example with deiconify()) to make some window managers notice changes to window attributes. wm_withdraw() is an alias of withdraw().

class tkinter.Pack

Geometry manager that arranges widgets by packing them against the sides of their container. The Pack mix-in is inherited by all widgets (through Widget) and provides the methods for managing a widget with the pack geometry manager. See also Geometry management.

Note

Pack, Place and Grid all define the short method names forget(), info(), slaves(), content() and propagate(). On a widget the bare names resolve to the pack manager’s versions, since Pack and Misc precede Place and Grid in the method resolution order, whatever manager actually manages the widget; and configure()/config() configure the widget’s options, not its geometry. Use the explicit pack_*, grid_* and place_* methods (and pack, grid, place for geometry configuration) to act on a specific geometry manager.

pack_configure(cnf={}, **kw)
pack(cnf={}, **kw)

Pack the widget inside its container, positioning it relative to the siblings already packed there. The supported options are:

side

Which side of the container to pack the widget against: 'top' (the default), 'bottom', 'left' or 'right'.

fill

Whether to stretch the widget to fill its parcel: 'none' (the default), 'x', 'y' or 'both'.

expand

Whether the widget should expand to consume any extra space in its container (a boolean, default false).

anchor

Where to position the widget in its parcel when the parcel is larger than the widget: an anchor such as 'n' or 'sw' (default 'center').

ipadx, ipady

Internal padding added on the left and right (ipadx) or top and bottom (ipady) of the widget, as a screen distance (default 0).

padx, pady

External padding left on the left and right (padx) or top and bottom (pady) of the widget, as a screen distance or a pair of two distances for the two sides (default 0).

after

Pack the widget after the given widget in the packing order, using the same container.

before

Pack the widget before the given widget in the packing order, using the same container.

in_

The container in which to pack the widget; it defaults to the parent widget.

pack(), configure() and config() are aliases of pack_configure().

pack_forget()

Unmap the widget and remove it from the packing order, forgetting its packing options. It can be packed again later with pack_configure(). forget() is an alias of pack_forget(), except on PanedWindow, ttk.Notebook and ttk.PanedWindow, which provide their own forget() method.

Not to be confused with Wm.forget().

pack_info()

Return a dictionary of the widget’s current packing options. info() is an alias of pack_info().

pack_propagate()
pack_propagate(flag)

Same as Misc.pack_propagate(), treating this widget as a container: enable or disable geometry propagation. propagate() is an alias of pack_propagate().

pack_slaves()

Same as Misc.pack_slaves(): return the list of widgets packed in this widget. slaves() is an alias of pack_slaves().

class tkinter.Place

Geometry manager that places widgets at explicit positions and sizes within their container. The Place mix-in is inherited by all widgets (through Widget). See also Geometry management.

place_configure(cnf={}, **kw)
place(cnf={}, **kw)

Place the widget inside its container at an absolute or relative position. The supported options are:

x, y

The absolute horizontal and vertical position of the widget’s anchor point, as a screen distance (default 0).

relx, rely

The horizontal and vertical position of the widget’s anchor point as a fraction of the container’s width and height, where 0.0 is the left or top edge and 1.0 is the right or bottom edge. If both the absolute and the relative option are given, their values are summed.

anchor

Which point of the widget is placed at the given position: an anchor such as 'n' or 'se' (default 'nw').

width, height

The absolute width and height of the widget, as a screen distance. By default the widget’s requested size is used.

relwidth, relheight

The width and height of the widget as a fraction of the container’s width and height. If both the absolute and the relative option are given, their values are summed.

bordermode

How the container’s border affects placement: 'inside' (the default) measures the area inside the border, 'outside' measures the area including the border, and 'ignore' uses the official X area.

in_

The container relative to which the widget is placed; it must be the widget’s parent or a descendant of the parent, and defaults to the parent.

place(), configure() and config() are aliases of place_configure().

place_forget()

Unmap the widget and remove it from the placement, forgetting its place options.

place_info()

Return a dictionary of the widget’s current place options.

place_slaves()

Same as Misc.place_slaves(): return the list of widgets placed in this widget.

class tkinter.Grid

Geometry manager that arranges widgets in a two-dimensional grid of rows and columns within their container. The Grid mix-in is inherited by all widgets (through Widget). See also Geometry management.

grid_configure(cnf={}, **kw)
grid(cnf={}, **kw)

Position the widget in a cell of its container’s grid.

Not to be confused with Wm.grid().

The supported options are:

row, column

The row and column of the cell to place the widget in, counting from 0. column defaults to the column after the previous widget placed in the same grid_configure() call (or 0), and row defaults to the next empty row.

rowspan, columnspan

The number of rows and columns the widget should span (default 1).

sticky

How to position or stretch the widget when its cell is larger than the widget: a string containing zero or more of the characters 'n', 's', 'e' and 'w', naming the cell sides the widget sticks to. Specifying both 'n' and 's' (or 'e' and 'w') stretches the widget to fill the height (or width) of the cell. The default is '', which centers the widget at its requested size.

ipadx, ipady

Internal padding added on the left and right (ipadx) or top and bottom (ipady) of the widget, as a screen distance (default 0).

padx, pady

External padding left on the left and right (padx) or top and bottom (pady) of the widget, as a screen distance or a pair of two distances for the two sides (default 0).

in_

The container in whose grid to place the widget; it defaults to the parent widget.

grid(), configure() and config() are aliases of grid_configure().

grid_forget()

Unmap the widget and remove it from the grid, forgetting its grid options.

grid_remove()

Unmap the widget and remove it from the grid, but remember its grid options so that it is restored to the same cell if it is gridded again.

grid_info()

Return a dictionary of the widget’s current grid options.

grid_bbox(column=None, row=None, col2=None, row2=None)

Same as Misc.grid_bbox(). bbox() is an alias of grid_bbox(), except on Canvas, Listbox, Spinbox, Text, ttk.Entry and ttk.Treeview, which provide their own bbox() method.

grid_columnconfigure(index, cnf={}, **kw)

Same as Misc.grid_columnconfigure(): query or set the options (such as weight, minsize, pad and uniform) of a grid column. columnconfigure() is an alias of grid_columnconfigure().

grid_rowconfigure(index, cnf={}, **kw)

Same as Misc.grid_rowconfigure(): query or set the options of a grid row. rowconfigure() is an alias of grid_rowconfigure().

grid_location(x, y)

Same as Misc.grid_location(): return the (column, row) of the cell that covers the pixel at x, y. location() is an alias of grid_location().

grid_size()

Same as Misc.grid_size(): return a (columns, rows) tuple giving the size of the grid. size() is an alias of grid_size(), except on the Listbox widget, which provides its own size() method.

grid_propagate()
grid_propagate(flag)

Same as Misc.grid_propagate().

grid_slaves(row=None, column=None)

Same as Misc.grid_slaves(): return the widgets managed in the grid, optionally restricted to a row and/or column.

class tkinter.XView

Mix-in providing the horizontal-scrolling interface shared by widgets such as Entry, Canvas, Listbox, Text and Spinbox. A widget’s xview() method is registered as the command of a horizontal Scrollbar.

xview(*args)

Query or change the horizontal position of the view. With no arguments, return a tuple (first, last) of two fractions between 0 and 1 giving the portion of the document that is currently visible. Otherwise the arguments are passed to the Tk xview widget command and are usually generated by a scrollbar; xview_moveto() and xview_scroll() provide a more convenient interface.

xview_moveto(fraction)

Adjust the view so that fraction of the total width of the document is off-screen to the left. fraction is a number between 0 and 1.

xview_scroll(number, what)

Shift the view left or right by number units. what is either 'units' or 'pages'; a negative number scrolls left and a positive one scrolls right.

class tkinter.YView

Mix-in providing the vertical-scrolling interface shared by widgets such as Canvas, Listbox and Text. A widget’s yview() method is registered as the command of a vertical Scrollbar.

yview(*args)

Query or change the vertical position of the view. With no arguments, return a tuple (first, last) of two fractions between 0 and 1 giving the portion of the document that is currently visible. Otherwise the arguments are passed to the Tk yview widget command, usually generated by a scrollbar; yview_moveto() and yview_scroll() provide a more convenient interface.

yview_moveto(fraction)

Adjust the view so that fraction of the total height of the document is off-screen above the top. fraction is a number between 0 and 1.

yview_scroll(number, what)

Shift the view up or down by number units. what is either 'units' or 'pages'; a negative number scrolls up and a positive one scrolls down.

class tkinter.BaseWidget(master, widgetName, cnf={}, kw={}, extra=())

Internal base class for all widgets. It inherits from Misc and adds the machinery that creates the underlying Tk widget; application code normally uses Widget or a concrete widget class rather than instantiating BaseWidget directly.

destroy()

Destroy this widget and all of its children, removing the corresponding Tk widgets and deleting the associated Tcl commands.

class tkinter.Widget(master, widgetName, cnf={}, kw={}, extra=())

Internal base class for the standard widgets. It combines BaseWidget with the geometry-manager mix-ins Pack, Place and Grid, so that every widget can be managed by any of the three geometry managers. The concrete widget classes (Button, Label, and so on) derive from Widget.

Toplevel widgets

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. Inherits from Misc and Wm.

To create a Tcl interpreter without initializing the Tk subsystem, use the Tcl() factory function instead.

The Tk class is typically instantiated using all default values. However, the following keyword arguments are currently recognized:

screenName

When given (as a string), sets the DISPLAY environment 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. The tkinter.Tcl() function sets this to False.

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.

Tk reads and interprets profile files, named .className.tcl and .baseName.tcl, into the Tcl interpreter and calls exec() on the contents of .className.py and .baseName.py. The path for the profile files is the HOME environment variable or, if that isn’t defined, then os.curdir.

Note

On Windows, creating a Tcl interpreter (by instantiating Tk or calling Tcl()) sets the HOME environment variable for the process, if it is not already set, to %HOMEDRIVE%%HOMEPATH% (or USERPROFILE, or c:\). This is done by Tcl and can affect other code that reads HOME.

tk

The Tk application object created by instantiating Tk. This provides access to the Tcl interpreter. Each widget that is attached the same instance of Tk has the same value for its tk attribute.

master

The widget object that contains this widget. For Tk, the master is None because it is the main window. The terms master and parent are similar and sometimes used interchangeably as argument names; however, calling winfo_parent() returns a string of the widget name whereas master returns the object. parent/child reflects the tree-like relationship while master (or container)/content reflects the container structure.

children

The immediate descendants of this widget as a dict with the child widget names as the keys and the child instance objects as the values.

destroy()

Destroy this and all descendant widgets and, for the main window, end the connection to the underlying Tcl interpreter.

loadtk()

Finish loading and initializing the Tk subsystem. This is needed only when the interpreter was created without Tk (for example through Tcl()); it is called automatically when useTk is true.

readprofile(baseName, className)

Read and source the user’s profile files .className.tcl and .baseName.tcl into the Tcl interpreter, and execute the corresponding .className.py and .baseName.py files. This is called during initialization; see the description of the constructor above.

report_callback_exception(exc, val, tb)

Report a callback exception. This is called when an exception propagates out of a Tkinter callback; exc, val and tb are the exception type, value and traceback as returned by sys.exc_info(). The default implementation prints a traceback to sys.stderr. It can be overridden to customize error handling, for example to display the traceback in a dialog.

class tkinter.Toplevel(master=None, cnf={}, **kw)

A Toplevel widget is a top-level window, similar to a Frame except that its X parent is the root window of a screen rather than its logical parent. Its primary purpose is to serve as a container for dialog boxes and other collections of widgets; its only visible features are its background and an optional 3-D border. Notable options include menu, which installs a Menu as the window’s menubar. Inherits from BaseWidget and Wm, so a toplevel is managed by the window manager. Refer to the Tk toplevel manual page for the full list of options.

Widget classes

class tkinter.Button(master=None, cnf={}, **kw)

A Button widget displays a textual string, bitmap or image and invokes a command when the user presses it (by clicking mouse button 1 over the button or, when the button has focus, by pressing the space key). Inherits from Widget. In addition to the standard widget options, a button accepts the options documented in the Tk button manual page, such as command (the callback invoked when the button is pressed), textvariable, state and default.

invoke()

Invoke the command associated with the button, if there is one, and return its result, or an empty string if no command is associated with the button. This is ignored if the button’s state is disabled.

flash()

Flash the button by redisplaying it several times, alternating between the active and normal colors. At the end of the flash the button is left in the same normal or active state as when the method was called. This is ignored if the button’s state is disabled.

class tkinter.Canvas(master=None, cnf={}, **kw)

A Canvas widget implements structured graphics. It displays any number of items, such as arcs, lines, ovals, polygons, rectangles, text, bitmaps, images and embedded windows, which may be drawn, moved, re-colored and bound to events. Inherits from Widget, XView and YView, so the view can be scrolled horizontally and vertically with xview() and yview(). Refer to the Tk canvas manual page for the full list of widget and item options.

Each item has a unique integer id, assigned when it is created, and zero or more string tags. A tag is an arbitrary string that does not have the form of an integer; the same tag may be shared by many items, which makes tags convenient for grouping items. The special tag 'all' matches every item in the canvas, and 'current' matches the topmost item under the mouse pointer. Most methods take a tagOrId argument that may be an integer id naming a single item, or a tag naming zero or more items; as described in the Tk canvas manual page, a tag may also be a logical expression of tags combined with the operators &&, ||, ^, ! and parentheses. When a method that operates on a single item is given a tagOrId matching several items, it normally uses the lowest matching item in the display list.

The items are kept in a display list that determines drawing order: items later in the list are drawn on top of earlier ones. A newly created item is placed at the top of the list; the order can be changed with tag_raise() and tag_lower().

create_arc(*args, **kw)
create_bitmap(*args, **kw)
create_image(*args, **kw)
create_line(*args, **kw)
create_oval(*args, **kw)
create_polygon(*args, **kw)
create_rectangle(*args, **kw)
create_text(*args, **kw)
create_window(*args, **kw)

Create a new item of the corresponding type and return its integer id. Each method is called as create_TYPE(coord..., **options): the leading positional arguments give the coordinates that define the item (as separate numbers, as a single sequence of numbers, or as coordinate pairs), and the keyword arguments set item-specific options. Coordinates and screen distances may be given as numbers (interpreted as pixels) or as strings with a unit suffix ('m', 'c', 'i' or 'p' for millimetres, centimetres, inches or printer’s points), but are always stored and returned in pixels.

The item types are: arc (an arc-shaped region that is a section of an oval, defined by two diagonally opposite corners x1, y1, x2, y2 of the enclosing rectangle); bitmap (a two-color bitmap positioned at a point x, y); image (a Tk image positioned at a point x, y); line (a line or curve through the points x1, y1, ..., xn, yn); oval (a circle or ellipse inscribed in the rectangle x1, y1, x2, y2); polygon (a closed polygon through the points x1, y1, ..., xn, yn); rectangle (a rectangle with corners x1, y1, x2, y2); text (a string of text positioned at a point x, y); and window (a child widget embedded in the canvas at a point x, y, specified with the window option).

Most item types accept a common set of standard item options, plus a few options specific to each type. Option names are passed as keyword arguments, without the leading hyphen.

The standard item options are:

fill

The color used to fill the item’s interior, or to draw a line item or the characters of a text item. An empty string (the default for all types except line and text) leaves the item unfilled.

outline

The color used to draw the item’s outline. An empty string draws no outline.

width

The width of the outline, defaulting to 1.0. Has no effect if outline is empty.

dash

A dash pattern for the outline, given either as a sequence of segment lengths in pixels or as a string of the characters '.', ',', '-', '_' and space. An empty pattern (the default) draws a solid outline.

dashoffset

The starting offset in pixels into the dash pattern. Ignored if there is no dash pattern.

stipple

A bitmap used as a stipple pattern when filling the item. Only well supported on X11.

outlinestipple

A bitmap used as a stipple pattern when drawing the outline. Has no effect if outline is empty.

offset, outlineoffset

The offset of the fill and outline stipple patterns, given as 'x,y' or as a side such as 'n', 'se' or 'center'. Stipple offsets are only supported on X11.

state

Overrides the canvas state for this item; one of 'normal', 'disabled' or 'hidden'.

tags

A single tag or a sequence of tags to associate with the item, replacing any existing tags.

Many of these options have active… and disabled… variants (such as activefill, disabledfill, activewidth, disableddash, activeoutline, disabledstipple) that override the base option when the item is the active item (under the mouse pointer) or is in the disabled state.

The following item types support additional options.

For arc items:

start

The start of the arc’s angular range, in degrees measured counter-clockwise from the 3-o’clock position.

extent

The size of the angular range, in degrees counter-clockwise from start.

style

How the arc is drawn: 'pieslice' (the default), 'chord' or 'arc'.

For line items:

arrow

Where to draw arrowheads: 'none' (the default), 'first', 'last' or 'both'.

arrowshape

A sequence of three distances describing the shape of the arrowheads.

capstyle

How line ends are drawn: 'butt' (the default), 'projecting' or 'round'.

joinstyle

How line vertices are drawn: 'round' (the default), 'bevel' or 'miter'.

smooth

The smoothing method: a false value (the default) for no smoothing, or 'true'/'bezier' or 'raw' to draw the line as a curve.

splinesteps

The number of line segments approximating each spline when smooth is enabled.

For polygon items:

joinstyle, smooth, splinesteps

As for line items, applied to the polygon’s outline.

For text items:

text

The string to display; newline characters start new lines.

font

The font used for the text.

justify

How lines are justified: 'left' (the default), 'right' or 'center'.

anchor

How the text is positioned relative to its point, defaulting to 'center'.

width

The maximum line length; if non-zero, lines are wrapped at spaces.

angle

How many degrees to rotate the text counter-clockwise about its positioning point, from 0.0 to 360.0 (default 0.0).

underline

The index of a character to underline, or -1 for none.

For bitmap items:

bitmap

The bitmap to display.

anchor

How the bitmap is positioned relative to its point.

background, foreground

The colors used for the bitmap’s 0 and 1 pixels; an empty background makes the 0 pixels transparent. Both have active… and disabled… variants, and bitmap has activebitmap and disabledbitmap variants.

For image items:

image

The Tk image to display, previously created with the image protocols.

anchor

How the image is positioned relative to its point.

Both options have active… and disabled… variants (activeimage, disabledimage) used in the active and disabled states.

For window items:

window

The widget to embed; it must be a child of the canvas or of one of its ancestors, and may not be a top-level window.

anchor

How the window is positioned relative to its point.

width, height

The size to assign to the window; if zero (the default), the window is given its requested size.

oval and rectangle items have no type-specific options; they use only the standard item options.

Note

Tk 8.6 added the angle option and Tk 9.0 added the underline option for