The Notebook widget

The Notebook widget is only available in ttk, rather than the regular Tkinter. The widget is used to create a tabbed interface for displaying multiple Frame widgets in one window. A small example will demonstrate this nicely:

import tkinter as tk
import tkinter.ttk as ttk

win = tk.Tk()
win.geometry("400x400")

n = ttk.Notebook(win)
frame_one = ttk.Frame(n)
frame_two = ttk.Frame(n)

label_one = ttk.Label(frame_one, text="We are in frame 1")
label_two = ttk.Label(frame_two, text="We are in frame 2")

We create an instance of the Notebook widget, then two Frame widgets to act as tabs.

Inside these two Frame widgets will be a Label widget which informs us which Frame we are seeing.

We now need to add these Frame widgets to our Notebook, which we do using the add method:

n.add(frame_one, text="Frame One")
n.add(frame_two, text="Frame Two")

n.pack(fill=tk.BOTH, expand=1)

label_one.pack(fill=tk.BOTH, expand=1)
label_two.pack(fill=tk.BOTH, expand=1)

win.mainloop()

Here, we add both of our Frame widgets to our Notebook, passing the text argument to control what will be written in the tab.

Since our Frame widgets are added to our Notebook, we don't need to use a geometry manager to display them, so we pack our Label widgets and Notebook, then fire off our window's main loop.

Run this code and you should see you have a window containing two different tabs. Click between them to see how each one contains a different Frame:

Those are all of the widgets of note which we didn't get to use in our example applications. If you would like to, have a think about how each could have been implemented in one of our applications.

For example, we could have used the Notebook widget to add file tabs to our text editor. If you are feeling adventurous, give this a go!

Now that we have covered these, it's time to have a look at how we can distribute our applications to other users who may want to install them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset