-
Notifications
You must be signed in to change notification settings - Fork 3
/
editabletreeview.py
executable file
·345 lines (297 loc) · 12.5 KB
/
editabletreeview.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
# encoding: utf8
#
# Copyright 2012-2013 Alejandro Autalán
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check https://github.com/alejandroautalan/pygubu
from __future__ import unicode_literals
import functools
try:
import tkinter as tk
import tkinter.ttk as ttk
except:
import Tkinter as tk
import ttk
class EditableTreeview(ttk.Treeview):
"""A simple editable treeview
It uses the following events from Treeview:
<<TreviewSelect>>
<4>
<5>
<KeyRelease>
<Home>
<End>
<Configure>
<Button-1>
<ButtonRelease-1>
<Motion>
If you need them use add=True when calling bind method.
It Generates two virtual events:
<<TreeviewInplaceEdit>>
<<TreeviewCellEdited>>
The first is used to configure cell editors.
The second is called after a cell was changed.
You can know wich cell is being configured or edited, using:
get_event_info()
"""
def __init__(self, master=None, **kw):
ttk.Treeview.__init__(self, master, **kw)
self._curfocus = None
self._inplace_widgets = {}
self._inplace_widgets_show = {}
self._inplace_vars = {}
self._header_clicked = False
self._header_dragged = False
self.bind('<<TreeviewSelect>>', self.__check_focus)
#Wheel events?
self.bind('<4>', lambda e: self.after_idle(self.__updateWnds))
self.bind('<5>', lambda e: self.after_idle(self.__updateWnds))
#self.bind('<ButtonRelease-1>', self.__check_focus)
self.bind('<KeyRelease>', self.__check_focus)
self.bind('<Home>', functools.partial(self.__on_key_press, 'Home'))
self.bind('<End>', functools.partial(self.__on_key_press, 'End'))
self.bind('<Button-1>', self.__on_button1)
self.bind('<ButtonRelease-1>', self.__on_button1_release)
self.bind('<Motion>', self.__on_mouse_motion)
self.bind('<Configure>',
lambda e: self.after_idle(self.__updateWnds))
def __on_button1(self, event):
r = event.widget.identify_region(event.x, event.y)
if r in ('separator', 'header'):
self._header_clicked = True
def __on_mouse_motion(self, event):
if self._header_clicked:
self._header_dragged = True
def __on_button1_release(self, event):
if self._header_dragged:
self.after_idle(self.__updateWnds)
self._header_clicked = False
self._header_dragged = False
def __on_key_press(self, key, event):
if key == 'Home':
self.selection_set("")
self.focus(self.get_children()[0])
if key == 'End':
self.selection_set("")
self.focus(self.get_children()[-1])
def delete(self, *items):
self.after_idle(self.__updateWnds)
ttk.Treeview.delete(self, *items)
def yview(self, *args):
"""Update inplace widgets position when doing vertical scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.yview(self, *args)
def yview_scroll(self, number, what):
self.after_idle(self.__updateWnds)
ttk.Treeview.yview_scroll(self, number, what)
def yview_moveto(self, fraction):
self.after_idle(self.__updateWnds)
ttk.Treeview.yview_moveto(self, fraction)
def xview(self, *args):
"""Update inplace widgets position when doing horizontal scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.xview(self, *args)
def xview_scroll(self, number, what):
self.after_idle(self.__updateWnds)
ttk.Treeview.xview_scroll(self, number, what)
def xview_moveto(self, fraction):
self.after_idle(self.__updateWnds)
ttk.Treeview.xview_moveto(self, fraction)
def __check_focus(self, event):
"""Checks if the focus has changed"""
#print('Event:', event.type, event.x, event.y)
changed = False
if not self._curfocus:
changed = True
elif self._curfocus != self.focus():
self.__clear_inplace_widgets()
changed = True
newfocus = self.focus()
if changed:
if newfocus:
#print('Focus changed to:', newfocus)
self._curfocus= newfocus
self.__focus(newfocus)
self.__updateWnds()
def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inplace_widgets[col]
w.bind('<Key-Tab>',
lambda e: w.tk_focusNext().focus_set())
w.bind('<Shift-Key-Tab>',
lambda e: w.tk_focusPrev().focus_set())
def __updateWnds(self, event=None):
if not self._curfocus:
return
item = self._curfocus
cols = self.__get_display_columns()
for col in cols:
if col in self._inplace_widgets:
wnd = self._inplace_widgets[col]
bbox = ''
if self.exists(item):
bbox = self.bbox(item, column=col)
if bbox == '':
wnd.place_forget()
elif col in self._inplace_widgets_show:
wnd.place(x=bbox[0], y=bbox[1],
width=bbox[2], height=bbox[3])
def __clear_inplace_widgets(self):
"""Remove all inplace edit widgets."""
cols = self.__get_display_columns()
#print('Clear:', cols)
for c in cols:
if c in self._inplace_widgets:
widget = self._inplace_widgets[c]
widget.place_forget()
self._inplace_widgets_show.pop(c, None)
#widget.destroy()
#del self._inplace_widgets[c]
def __get_display_columns(self):
cols = self.cget('displaycolumns')
show = (str(s) for s in self.cget('show'))
if '#all' in cols:
cols = self.cget('columns') + ('#0',)
elif 'tree' in show:
cols = cols + ('#0',)
return cols
def get_event_info(self):
return self.__event_info;
def __get_value(self, col, item):
if col == '#0':
return self.item(item, 'text')
else:
return self.set(item, col)
def __set_value(self, col, item, value):
if col == '#0':
self.item(item, text=value)
else:
self.set(item, col, value)
self.__event_info =(col,item)
self.event_generate('<<TreeviewCellEdited>>')
def __update_value(self, col, item):
if not self.exists(item):
return
value = self.__get_value(col, item)
newvalue = self._inplace_vars[col].get()
if value != newvalue:
self.__set_value(col, item, newvalue)
def inplace_entry(self, col, item):
if col not in self._inplace_vars:
self._inplace_vars[col] = tk.StringVar()
svar = self._inplace_vars[col]
svar.set(self.__get_value(col, item))
if col not in self._inplace_widgets:
self._inplace_widgets[col] = ttk.Entry(self, textvariable=svar)
entry = self._inplace_widgets[col]
entry.bind('<Unmap>', lambda e: self.__update_value(col, item))
entry.bind('<FocusOut>', lambda e: self.__update_value(col, item))
self._inplace_widgets_show[col] = True
def inplace_checkbutton(self, col, item, onvalue='True', offvalue='False'):
if col not in self._inplace_vars:
self._inplace_vars[col] = tk.StringVar()
svar = self._inplace_vars[col]
svar.set(self.__get_value(col, item))
if col not in self._inplace_widgets:
self._inplace_widgets[col] = ttk.Checkbutton(self,
textvariable=svar, variable=svar, onvalue=onvalue, offvalue=offvalue)
cb = self._inplace_widgets[col]
cb.bind('<Unmap>', lambda e: self.__update_value(col, item))
cb.bind('<FocusOut>', lambda e: self.__update_value(col, item))
self._inplace_widgets_show[col] = True
def inplace_combobox(self, col, item, values, readonly=True):
state = 'readonly' if readonly else 'normal'
if col not in self._inplace_vars:
self._inplace_vars[col] = tk.StringVar()
svar = self._inplace_vars[col]
svar.set(self.__get_value(col, item))
if col not in self._inplace_widgets:
self._inplace_widgets[col] = ttk.Combobox(self,
textvariable=svar, values=values, state=state)
cb = self._inplace_widgets[col]
cb.bind('<Unmap>', lambda e: self.__update_value(col, item))
cb.bind('<FocusOut>', lambda e: self.__update_value(col, item))
self._inplace_widgets_show[col] = True
def inplace_spinbox(self, col, item, min, max, step):
if col not in self._inplace_vars:
self._inplace_vars[col] = tk.StringVar()
svar = self._inplace_vars[col]
svar.set(self.__get_value(col, item))
if col not in self._inplace_widgets:
self._inplace_widgets[col] = tk.Spinbox(self,
textvariable=svar, from_=min, to=max, increment=step)
sb = self._inplace_widgets[col]
sb.bind('<Unmap>', lambda e: self.__update_value(col, item))
cb.bind('<FocusOut>', lambda e: self.__update_value(col, item))
self._inplace_widgets_show[col] = True
def inplace_custom(self, col, item, widget):
if col not in self._inplace_vars:
self._inplace_vars[col] = tk.StringVar()
svar = self._inplace_vars[col]
svar.set(self.__get_value(col, item))
self._inplace_widgets[col] = widget
widget.bind('<Unmap>', lambda e: self.__update_value(col, item))
widget.bind('<FocusOut>', lambda e: self.__update_value(col, item))
self._inplace_widgets_show[col] = True
if __name__ == "__main__":
# other examples: https://github.com/hunterjm/futgui/blob/master/frames/playersearch.py
_=lambda x: x
class MyApplication(object):
def __init__(self, master):
self.mainwindow = tk.Tk()
self.etv = EditableTreeview(self.mainwindow)
self.etv["columns"]=("type","url")
self.etv.column("type", anchor='center', width=60)
self.etv.column("url")
self.etv.column('#0', anchor='w', width=30)
self.etv.heading('#0', text=_("Header"), anchor='w')
self.etv.heading("type", text=_("Type"))
self.etv.heading("url", text=_("URL"))
self.etv.bind('<<TreeviewInplaceEdit>>', self.on_row_edit)
self.etv.bind('<<TreeviewCellEdited>>', self.on_cell_changed)
self.etv.pack()
self.allow_edit = tk.BooleanVar()
self.allow_edit.set(True)
# Add some data to the treeview
data = [
('news', 'http://www.tn.com.ar'),
('games', 'https://www.gog.com'),
('search', 'https://duckduckgo.com')
]
for d in data:
self.etv.insert('', tk.END, values=d)
def on_row_edit(self, event):
# Get the column id and item id of the cell
# that is going to be edited
col, item = self.etv.get_event_info()
# Allow edition only if allow_edit variable is checked
if self.allow_edit.get() == True:
# Define the widget editor to be used to edit the column value
if col in ('url',):
self.etv.inplace_entry(col, item)
def on_cell_changed(self, event):
col, item = self.etv.get_event_info()
print('Column {0} of item {1} was changed'.format(col, item))
def on_row_selected(self, event):
print('Rows selected', event.widget.selection())
def run(self):
self.mainwindow.mainloop()
app = MyApplication(None)
app.run()