• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""A Ttk Notebook with close buttons.
2
3Based on an example by patthoyts, http://paste.tclers.tk/896
4"""
5import os
6import Tkinter
7import ttk
8
9root = Tkinter.Tk()
10
11imgdir = os.path.join(os.path.dirname(__file__), 'img')
12i1 = Tkinter.PhotoImage("img_close", file=os.path.join(imgdir, 'close.gif'))
13i2 = Tkinter.PhotoImage("img_closeactive",
14    file=os.path.join(imgdir, 'close_active.gif'))
15i3 = Tkinter.PhotoImage("img_closepressed",
16    file=os.path.join(imgdir, 'close_pressed.gif'))
17
18style = ttk.Style()
19
20style.element_create("close", "image", "img_close",
21    ("active", "pressed", "!disabled", "img_closepressed"),
22    ("active", "!disabled", "img_closeactive"), border=8, sticky='')
23
24style.layout("ButtonNotebook", [("ButtonNotebook.client", {"sticky": "nswe"})])
25style.layout("ButtonNotebook.Tab", [
26    ("ButtonNotebook.tab", {"sticky": "nswe", "children":
27        [("ButtonNotebook.padding", {"side": "top", "sticky": "nswe",
28                                     "children":
29            [("ButtonNotebook.focus", {"side": "top", "sticky": "nswe",
30                                       "children":
31                [("ButtonNotebook.label", {"side": "left", "sticky": ''}),
32                 ("ButtonNotebook.close", {"side": "left", "sticky": ''})]
33            })]
34        })]
35    })]
36)
37
38def btn_press(event):
39    x, y, widget = event.x, event.y, event.widget
40    elem = widget.identify(x, y)
41    index = widget.index("@%d,%d" % (x, y))
42
43    if "close" in elem:
44        widget.state(['pressed'])
45        widget.pressed_index = index
46
47def btn_release(event):
48    x, y, widget = event.x, event.y, event.widget
49
50    if not widget.instate(['pressed']):
51        return
52
53    elem =  widget.identify(x, y)
54    index = widget.index("@%d,%d" % (x, y))
55
56    if "close" in elem and widget.pressed_index == index:
57        widget.forget(index)
58        widget.event_generate("<<NotebookClosedTab>>")
59
60    widget.state(["!pressed"])
61    widget.pressed_index = None
62
63
64root.bind_class("TNotebook", "<ButtonPress-1>", btn_press, True)
65root.bind_class("TNotebook", "<ButtonRelease-1>", btn_release)
66
67# create a ttk notebook with our custom style, and add some tabs to it
68nb = ttk.Notebook(width=200, height=200, style="ButtonNotebook")
69nb.pressed_index = None
70f1 = Tkinter.Frame(nb, background="red")
71f2 = Tkinter.Frame(nb, background="green")
72f3 = Tkinter.Frame(nb, background="blue")
73nb.add(f1, text='Red', padding=3)
74nb.add(f2, text='Green', padding=3)
75nb.add(f3, text='Blue', padding=3)
76nb.pack(expand=1, fill='both')
77
78root.mainloop()
79