Creating Widgets

Learn about the different types of widgets in Tkinter.

We'll cover the following

Widgets in Tkinter

There are fifteen types of widgets in Tkinter, and each has many options, indicated with option=value. This lesson will cover only the most common types and options. For more detail, the official Python docs for Tkinter is an excellent reference.

In the following widget example, we will assume that the window is called top.

  • fr = Frame(parent, option, ...)

    • This is a container for widgets. The parent may be the top-level window (top) or another frame. Some useful options are bg=color, the background color (as a color name or hex number), and bd=n, the border width in pixels.
  • but = Button(parent, text=string, command=function_name)

    • This creates a button containing the string that will call the named function when clicked. Parameters cannot be supplied to the function.
  • lab = Label(parent, text=string)

    • This creates a label that can be displayed but not edited.
    • To change the text, use lab.configure(text=new_text).
  • ent = Entry(parent, width=n)

    • This creates a rectangle large enough to display approximately n characters, into which the user can type a single line of text. More than n characters may be entered, but they may not all be visible.
    • To retrieve the text, call ent.get().
  • txt = Text(parent, width=num_characters, height=num_lines)

    • This creates a rectangle num_characters wide and num_lines high, into which the user can type multiple lines of text. Any number of lines may be entered, but only the specified number will be visible.
    • To retrieve the text, call txt.get(1.0, END).
    • To delete all text, use txt.delete(1.0, END).
    • To insert text, use txt.insert(END, text).
  • var = IntVar()

    • This defines var as an IntVar (see Checkbutton below).
  • chk = Checkbutton(parent, text=string, variable=var, command=function)

    • The var must be defined with IntVar().
    • This creates a checkbox with the given text.
    • var.get() will return 1 if checked and 0 if not checked.

Tkinter example

Here is a program for rolling a single die. When executed, the window should appear at the center of your screen. You can exit the program by closing the window.

Get hands-on with 1200+ tech skills courses.