Python Tkinter – Create Tabs with Notebook Widget

Posted on 09-23-2018 by superadm1n

In the Video I go through writing the code below which will add a notebook widget inside of your main window which will allow you to make tabs in your interface. The majority of the code is configuring the window itself, there is only about 6 lines that actually make the tabs which when I learned this I was surprised how easy it was to do.

Python2:

#!/usr/bin/python
from Tkinter import *
import ttk
 
 
main = Tk()
main.title('Notebook Demo')
main.geometry('500x500')
 
 
# gives weight to the cells in the grid
rows = 0
while rows < 50:
    main.rowconfigure(rows, weight=1)
    main.columnconfigure(rows, weight=1)
    rows += 1
 
# Defines and places the notebook widget
nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
 
# Adds tab 1 of the notebook
page1 = ttk.Frame(nb)
nb.add(page1, text='Tab1')
 
# Adds tab 2 of the notebook
page2 = ttk.Frame(nb)
nb.add(page2, text='Tab2')
 
 
main.mainloop()

Python3:

#!/usr/bin/python
 
from tkinter import *
from tkinter import ttk
 
 
main = Tk()
main.title('Notebook Demo')
main.geometry('500x500')
 
 
# gives weight to the cells in the grid
rows = 0
while rows < 50:
    main.rowconfigure(rows, weight=1)
    main.columnconfigure(rows, weight=1)
    rows += 1
 
# Defines and places the notebook widget
nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
 
# Adds tab 1 of the notebook
page1 = ttk.Frame(nb)
nb.add(page1, text='Tab1')
 
# Adds tab 2 of the notebook
page2 = ttk.Frame(nb)
nb.add(page2, text='Tab2')
 
 
main.mainloop()

Note the only difference between the code for python 2.x and 3.x is the import statements so if you wanted to make it more cross platform you could change the block of imports into a try except block

try:
    # Python 2.x
    from Tkinter import *
    import ttk
except ImportError:
    # Python 3.x
    from tkinter import *
    from tkinter import ttk

 

 

 

 

 

 


Leave a Comment:


Search