Notebook widget in Tkinter

Eli Courtwright picture Eli Courtwright · Nov 12, 2008 · Viewed 43.3k times · Source

Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).

A little Googling on the subject offers a few suggestions. There's a cookbook entry with a class allowing you to use tabs, but it's very primitive. There's also Python megawidgets on SourceForge, although this seems very old and gave me errors during installation.

Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?

Answer

tzot picture tzot · Nov 12, 2008

On recent Python (> 2.7) versions, you can use the ttk module, which provides access to the Tk themed widget set, which has been introduced in Tk 8.5.

Here's how you import ttk in Python 2:

import ttk

help(ttk.Notebook)

In Python 3, the ttk module comes with the standard distributions as a submodule of tkinter.

Here's a simple working example based on an example from the TkDocs website:

from tkinter import ttk
import tkinter as tk
from tkinter.scrolledtext import ScrolledText


def demo():
    root = tk.Tk()
    root.title("ttk.Notebook")

    nb = ttk.Notebook(root)

    # adding Frames as pages for the ttk.Notebook 
    # first page, which would get widgets gridded into it
    page1 = ttk.Frame(nb)

    # second page
    page2 = ttk.Frame(nb)
    text = ScrolledText(page2)
    text.pack(expand=1, fill="both")

    nb.add(page1, text='One')
    nb.add(page2, text='Two')

    nb.pack(expand=1, fill="both")

    root.mainloop()

if __name__ == "__main__":
    demo()

Another alternative is to use the NoteBook widget from the tkinter.tix library. To use tkinter.tix, you must have the Tix widgets installed, usually alongside your installation of the Tk widgets. To test your installation, try the following:

from tkinter import tix
root = tix.Tk()
root.tk.eval('package require Tix')

For more info, check out this webpage on the PSF website.

Note that tix is pretty old and not well-supported, so your best choice might be to go for ttk.Notebook.