Skip to content

Commit b7f686d

Browse files
author
guilherme.polo
committed
Demos for ttk added.
git-svn-id: http://svn.python.org/projects/python/trunk@69053 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent c39cfe0 commit b7f686d

16 files changed

+1197
-0
lines changed

Demo/tkinter/README

+1
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ Subdirectories:
88

99
guido my original example set (fairly random collection)
1010
matt Matt Conway's examples, to go with his lifesaver document
11+
ttk Examples using the ttk module

Demo/tkinter/ttk/combo_themes.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""Ttk Theme Selector.
2+
3+
Although it is a theme selector, you won't notice many changes since
4+
there is only a combobox and a frame around.
5+
"""
6+
import ttk
7+
8+
class App(ttk.Frame):
9+
def __init__(self):
10+
ttk.Frame.__init__(self)
11+
12+
self.style = ttk.Style()
13+
self._setup_widgets()
14+
15+
def _change_theme(self, event):
16+
if event.widget.current(): # value #0 is not a theme
17+
newtheme = event.widget.get()
18+
# change to the new theme and refresh all the widgets
19+
self.style.theme_use(newtheme)
20+
21+
def _setup_widgets(self):
22+
themes = list(self.style.theme_names())
23+
themes.insert(0, "Pick a theme")
24+
# Create a readonly Combobox which will display 4 values at max,
25+
# which will cause it to create a scrollbar if there are more
26+
# than 4 values in total.
27+
themes_combo = ttk.Combobox(self, values=themes, state="readonly",
28+
height=4)
29+
themes_combo.set(themes[0]) # sets the combobox value to "Pick a theme"
30+
# Combobox widget generates a <<ComboboxSelected>> virtual event
31+
# when the user selects an element. This event is generated after
32+
# the listbox is unposted (after you select an item, the combobox's
33+
# listbox disappears, then it is said that listbox is now unposted).
34+
themes_combo.bind("<<ComboboxSelected>>", self._change_theme)
35+
themes_combo.pack(fill='x')
36+
37+
self.pack(fill='both', expand=1)
38+
39+
40+
def main():
41+
app = App()
42+
app.master.title("Ttk Combobox")
43+
app.mainloop()
44+
45+
if __name__ == "__main__":
46+
main()

Demo/tkinter/ttk/dirbrowser.py

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"""A directory browser using Ttk Treeview.
2+
3+
Based on the demo found in Tk 8.5 library/demos/browse
4+
"""
5+
import os
6+
import glob
7+
import Tkinter
8+
import ttk
9+
10+
def populate_tree(tree, node):
11+
if tree.set(node, "type") != 'directory':
12+
return
13+
14+
path = tree.set(node, "fullpath")
15+
tree.delete(*tree.get_children(node))
16+
17+
parent = tree.parent(node)
18+
special_dirs = [] if parent else glob.glob('.') + glob.glob('..')
19+
20+
for p in special_dirs + os.listdir(path):
21+
ptype = None
22+
p = os.path.join(path, p).replace('\\', '/')
23+
if os.path.isdir(p): ptype = "directory"
24+
elif os.path.isfile(p): ptype = "file"
25+
26+
fname = os.path.split(p)[1]
27+
id = tree.insert(node, "end", text=fname, values=[p, ptype])
28+
29+
if ptype == 'directory':
30+
if fname not in ('.', '..'):
31+
tree.insert(id, 0, text="dummy")
32+
tree.item(id, text=fname)
33+
elif ptype == 'file':
34+
size = os.stat(p).st_size
35+
tree.set(id, "size", "%d bytes" % size)
36+
37+
38+
def populate_roots(tree):
39+
dir = os.path.abspath('.').replace('\\', '/')
40+
node = tree.insert('', 'end', text=dir, values=[dir, "directory"])
41+
populate_tree(tree, node)
42+
43+
def update_tree(event):
44+
tree = event.widget
45+
populate_tree(tree, tree.focus())
46+
47+
def change_dir(event):
48+
tree = event.widget
49+
node = tree.focus()
50+
if tree.parent(node):
51+
path = os.path.abspath(tree.set(node, "fullpath"))
52+
if os.path.isdir(path):
53+
os.chdir(path)
54+
tree.delete(tree.get_children(''))
55+
populate_roots(tree)
56+
57+
def autoscroll(sbar, first, last):
58+
"""Hide and show scrollbar as needed."""
59+
first, last = float(first), float(last)
60+
if first <= 0 and last >= 1:
61+
sbar.grid_remove()
62+
else:
63+
sbar.grid()
64+
sbar.set(first, last)
65+
66+
root = Tkinter.Tk()
67+
68+
vsb = ttk.Scrollbar(orient="vertical")
69+
hsb = ttk.Scrollbar(orient="horizontal")
70+
71+
tree = ttk.Treeview(columns=("fullpath", "type", "size"),
72+
displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
73+
xscrollcommand=lambda f, l:autoscroll(hsb, f, l))
74+
75+
vsb['command'] = tree.yview
76+
hsb['command'] = tree.xview
77+
78+
tree.heading("#0", text="Directory Structure", anchor='w')
79+
tree.heading("size", text="File Size", anchor='w')
80+
tree.column("size", stretch=0, width=100)
81+
82+
populate_roots(tree)
83+
tree.bind('<<TreeviewOpen>>', update_tree)
84+
tree.bind('<Double-Button-1>', change_dir)
85+
86+
# Arrange the tree and its scrollbars in the toplevel
87+
tree.grid(column=0, row=0, sticky='nswe')
88+
vsb.grid(column=1, row=0, sticky='ns')
89+
hsb.grid(column=0, row=1, sticky='ew')
90+
root.grid_columnconfigure(0, weight=1)
91+
root.grid_rowconfigure(0, weight=1)
92+
93+
root.mainloop()

Demo/tkinter/ttk/img/close.gif

101 Bytes
Loading

Demo/tkinter/ttk/img/close_active.gif

80 Bytes
Loading
101 Bytes
Loading

Demo/tkinter/ttk/listbox_scrollcmd.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Sample taken from: http://www.tkdocs.com/tutorial/morewidgets.html and
2+
converted to Python, mainly to demonstrate xscrollcommand option.
3+
4+
grid [tk::listbox .l -yscrollcommand ".s set" -height 5] -column 0 -row 0 -sticky nwes
5+
grid [ttk::scrollbar .s -command ".l yview" -orient vertical] -column 1 -row 0 -sticky ns
6+
grid [ttk::label .stat -text "Status message here" -anchor w] -column 0 -row 1 -sticky we
7+
grid [ttk::sizegrip .sz] -column 1 -row 1 -sticky se
8+
grid columnconfigure . 0 -weight 1; grid rowconfigure . 0 -weight 1
9+
for {set i 0} {$i<100} {incr i} {
10+
.l insert end "Line $i of 100"
11+
}
12+
"""
13+
import Tkinter
14+
import ttk
15+
16+
root = Tkinter.Tk()
17+
18+
l = Tkinter.Listbox(height=5)
19+
l.grid(column=0, row=0, sticky='nwes')
20+
21+
s = ttk.Scrollbar(command=l.yview, orient='vertical')
22+
l['yscrollcommand'] = s.set
23+
s.grid(column=1, row=0, sticky="ns")
24+
25+
stat = ttk.Label(text="Status message here", anchor='w')
26+
stat.grid(column=0, row=1, sticky='we')
27+
28+
sz = ttk.Sizegrip()
29+
sz.grid(column=1, row=1, sticky='se')
30+
31+
root.grid_columnconfigure(0, weight=1)
32+
root.grid_rowconfigure(0, weight=1)
33+
34+
for i in range(100):
35+
l.insert('end', "Line %d of 100" % i)
36+
37+
root.mainloop()

Demo/tkinter/ttk/mac_searchentry.py

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""Mac style search widget
2+
3+
Translated from Tcl code by Schelte Bron, http://wiki.tcl.tk/18188
4+
"""
5+
import Tkinter
6+
import ttk
7+
8+
root = Tkinter.Tk()
9+
10+
data = """
11+
R0lGODlhKgAaAOfnAFdZVllbWFpcWVtdWlxeW11fXF9hXmBiX2ZnZWhpZ2lraGxua25wbXJ0
12+
cXR2c3V3dHZ4dXh6d3x+e31/fH6AfYSGg4eJhoiKh4qMiYuNio2PjHmUqnqVq3yXrZGTkJKU
13+
kX+asJSWk32cuJWXlIGcs5aYlX6euZeZloOetZial4SftpqbmIWgt4GhvYahuIKivpudmYei
14+
uYOjv5yem4ijuoSkwIWlwYmlu56gnYamwp+hnoenw4unvaCin4ioxJCnuZykrImpxZmlsoaq
15+
zI2pv6KkoZGouoqqxpqms4erzaOloo6qwYurx5Kqu5untIiszqSmo5CrwoysyJeqtpOrvJyo
16+
tZGsw42typSsvaaopZKtxJWtvp6qt4+uy6epppOuxZCvzKiqp5quuZSvxoyx06mrqJWwx42y
17+
1JKxzpmwwaqsqZaxyI6z1ZqxwqutqpOzz4+01qyuq56yvpizypS00Jm0y5W10Zq1zJa20rCy
18+
rpu3zqizwbGzr6C3yZy4z7K0saG4yp250LO1sqK5y5660Z+70qO7zKy4xaC806S8zba4taG9
19+
1KW9zq66x6+7yLi6t6S/1rC8yrm7uLO8xLG9y7q8ubS9xabB2anB07K+zLW+xrO/za7CzrTA
20+
zrjAyLXBz77BvbbC0K/G2LjD0bnE0rLK28TGw8bIxcLL07vP28HN28rMycvOyr/T38DU4cnR
21+
2s/RztHT0NLU0cTY5MrW5MvX5dHX2c3Z59bY1dPb5Nbb3dLe7Nvd2t3f3NXh797g3d3j5dnl
22+
9OPl4eTm4+Ln6tzo9uXn5Obo5eDp8efp5uHq8uXq7ejq5+nr6OPs9Ovu6unu8O3v6+vw8+7w
23+
7ezx9O/x7vDy7/Hz8O/19/P18vT38/L3+fb49Pf59vX6/fj69/b7/vn7+Pr8+ff9//v9+vz/
24+
+/7//P//////////////////////////////////////////////////////////////////
25+
/////////////////////////////////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJZAD/ACwC
26+
AAIAKAAWAAAI/gD/CRz4bwUGCg8eQFjIsGHDBw4iTLAQgqBFgisuePCiyJOpUyBDihRpypMi
27+
Lx8qaLhIMIyGFZ5sAUsmjZrNmzhzWpO2DJgtTysqfGDpxoMbW8ekeQsXzty4p1CjRjUXrps3
28+
asJsuclQ4uKKSbamMR3n1JzZs2jRkh1HzuxVXX8y4CDYAwqua+DInVrRwMGJU2kDp31KThy1
29+
XGWGDlxhi1rTPAUICBBAoEAesoIzn6Vm68MKgVAUHftmzhOCBCtQwQKSoABgzZnJdSMmyIPA
30+
FbCotdUQAIhNa9B6DPCAGbZac+SowVIMRVe4pwkA4GpqDlwuAAmMZx4nTtfnf1mO5JEDNy46
31+
MHJkxQEDgKC49rPjwC0bqGaZuOoZAKjBPE4NgAzUvYcWOc0QZF91imAnCDHJ5JFAAJN0I2Ba
32+
4iRDUC/gOEVNDwIUcEABCAgAAATUTIgWOMBYRFp80ghiAQIIVAAEAwJIYI2JZnUji0XSYAYO
33+
NcsQA8wy0hCTwAASXGOiONFcxAtpTokTHznfiLMNMAkcAMuE43jDC0vLeGOWe2R5o4sn1LgH
34+
GzkWsvTPMgEOaA433Ag4TjjMuDkQMNi0tZ12sqWoJ0HATMPNffA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GEIJQQIAklZMXWRBAR
49+
RRRWENHwRQEBADs="""
50+
51+
52+
s1 = Tkinter.PhotoImage("search1", data=data, format="gif -index 0")
53+
s2 = Tkinter.PhotoImage("search2", data=data, format="gif -index 1")
54+
55+
style = ttk.Style()
56+
57+
style.element_create("Search.field", "image", "search1",
58+
("focus", "search2"), border=[22, 7, 14], sticky="ew")
59+
60+
style.layout("Search.entry", [
61+
("Search.field", {"sticky": "nswe", "border": 1, "children":
62+
[("Entry.padding", {"sticky": "nswe", "children":
63+
[("Entry.textarea", {"sticky": "nswe"})]
64+
})]
65+
})]
66+
)
67+
68+
style.configure("Search.entry", background="#b2b2b2")
69+
70+
root.configure(background="#b2b2b2")
71+
72+
e1 = ttk.Entry(style="Search.entry", width=20)
73+
e2 = ttk.Entry(style="Search.entry", width=20)
74+
75+
e1.grid(padx=10, pady=10)
76+
e2.grid(padx=10, pady=10)
77+
78+
root.mainloop()

Demo/tkinter/ttk/notebook_closebtn.py

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""A Ttk Notebook with close buttons.
2+
3+
Based on an example by patthoyts, http://paste.tclers.tk/896
4+
"""
5+
import os
6+
import Tkinter
7+
import ttk
8+
9+
root = Tkinter.Tk()
10+
11+
imgdir = os.path.join(os.path.dirname(__file__), 'img')
12+
i1 = Tkinter.PhotoImage("img_close", file=os.path.join(imgdir, 'close.gif'))
13+
i2 = Tkinter.PhotoImage("img_closeactive",
14+
file=os.path.join(imgdir, 'close_active.gif'))
15+
i3 = Tkinter.PhotoImage("img_closepressed",
16+
file=os.path.join(imgdir, 'close_pressed.gif'))
17+
18+
style = ttk.Style()
19+
20+
style.element_create("close", "image", "img_close",
21+
("active", "pressed", "!disabled", "img_closepressed"),
22+
("active", "!disabled", "img_closeactive"), border=8, sticky='')
23+
24+
style.layout("ButtonNotebook", [("ButtonNotebook.client", {"sticky": "nswe"})])
25+
style.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+
38+
def 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+
47+
def 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+
64+
root.bind_class("TNotebook", "<ButtonPress-1>", btn_press, True)
65+
root.bind_class("TNotebook", "<ButtonRelease-1>", btn_release)
66+
67+
# create a ttk notebook with our custom style, and add some tabs to it
68+
nb = ttk.Notebook(width=200, height=200, style="ButtonNotebook")
69+
nb.pressed_index = None
70+
f1 = Tkinter.Frame(nb, background="red")
71+
f2 = Tkinter.Frame(nb, background="green")
72+
f3 = Tkinter.Frame(nb, background="blue")
73+
nb.add(f1, text='Red', padding=3)
74+
nb.add(f2, text='Green', padding=3)
75+
nb.add(f3, text='Blue', padding=3)
76+
nb.pack(expand=1, fill='both')
77+
78+
root.mainloop()

0 commit comments

Comments
 (0)