how to enable & disable tabs in a Tkinter/Tix Python GUI

jez picture jez · Jan 7, 2014 · Viewed 10.1k times · Source

I'm trying to make a tabbed GUI in Python and I want to be able to toggle the enabled/disabled state of the tabs (i.e. prevent the user from switching tabs, and ghost non-active tabs out to make this fact obvious). So far I've been unable to figure out how to do this state toggling.

I've decided to go with Tkinter and/or Tix because they come built into Python distros on Windows, (guiding my users through installing extra third-party dependencies will be more trouble than it's worth). I've worked with Tkinter a bit but never Tix until now-tabs seem to require it. So I've built a two-tabbed Tix.NoteBook based on the demo at http://svn.python.org/projects/python/trunk/Demo/tix/samples/NoteBook.py

For disabling a tab, the only relevant attribute of the Tix tab instance (e.g. nb.hard_disk in the demo code) seems to be configure() but naively doing something Tkinter-like, i.e. nb.hard_disk.configure(state=Tix.DISABLED), results in TclError: unknown option "-state"

Searches for "disable Tix notebook tab" yield nothing, and even the more general "disable Tix widget" yields nothing I can understand/use. Grateful for any pointers in the right direction.

Answer

Karim Bahgat picture Karim Bahgat · Jan 10, 2014

In general how you disable widgets in Tkinter is by setting the "state" option to Tk.DISABLED or more foolproof just setting it to a string saying "disabled". The following grays out and disables your tab:

notebook.tab(0, state="disabled")

with 0 being the index of the tab you want to disable, and notebook being your notebook object. Does that answer your question?

Below is a simple notebook example to demonstrate:

import Tkinter
import ttk

window = Tkinter.Tk()
notebook = ttk.Notebook(window)
notebook.pack()
subframe = Tkinter.Frame(window)
subframe.pack()
notebook.add(subframe, text="tab", state="normal")
def buttonaction():
    notebook.tab(0, state="disabled")
button = Tkinter.Button(subframe, command=buttonaction, text="click to disable tab")
button.pack()

if __name__ == "__main__":
    window.mainloop()