本文整理汇总了Python中tkinter.Listbox.selection_set方法的典型用法代码示例。如果您正苦于以下问题:Python Listbox.selection_set方法的具体用法?Python Listbox.selection_set怎么用?Python Listbox.selection_set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Listbox
的用法示例。
在下文中一共展示了Listbox.selection_set方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: LabeledListBox
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
class LabeledListBox(Frame):
def __init__(self, parent, list_model, label_text):
Frame.__init__(self, parent)
self._list_model = list_model
self._list_objects = []
self._selected_items = []
scrollbar = Scrollbar(self, orient=VERTICAL)
Label(self, text=label_text).pack()
self.listbox = Listbox(self, selectmode=EXTENDED, exportselection=0, yscrollcommand=scrollbar.set, borderwidth=0, highlightthickness=0)
scrollbar.config(command=self.listbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
self.listbox.pack(side=LEFT, fill=BOTH, expand=1)
self.listbox.bind('<<ListboxSelect>>', self._on_select)
self._list_model.list_items_model.add_listener(self._list_items_changed)
self._list_model.selected_items_model.add_listener(self._selected_items_changed)
self._update_list_items()
def _list_items_changed(self, values):
self._update_list_items()
def _selected_items_changed(self, values):
self._update_selected_items()
def _update_list_items(self):
values, labels = self._list_model.list_items_model.get_list_values()
if not values == self._list_objects:
self._list_objects = []
self._selected_items = []
self.listbox.delete(0, END)
for value, label in zip(values, labels):
self._list_objects.append(value)
self.listbox.insert(END, label)
self._update_selected_items()
def _update_selected_items(self):
selected_items = self._list_model.selected_items_model.selected_items
if not selected_items == self._selected_items:
self._selected_items = selected_items
for index, list_item in enumerate(self._list_objects):
if list_item in selected_items:
self.listbox.selection_set(index)
def _on_select(self, evt):
visible_selected_indices = self.listbox.curselection()
for index, list_item in enumerate(self._list_objects):
if index in visible_selected_indices:
self._list_model.selected_items_model.select(list_item)
else:
self._list_model.selected_items_model.deselect(list_item)
示例2: RecursiveDescentApp
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
self._position_text()
def _redraw_quick(self):
# This should be more-or-less sufficient after an animation.
self._highlight_nodes()
self._highlight_prodlist()
self._position_text()
def _highlight_nodes(self):
# Highlight the list of nodes to be checked.
bold = ('helvetica', -self._size.get(), 'bold')
for treeloc in self._parser.frontier()[:1]:
self._get(self._tree, treeloc)['color'] = '#20a050'
self._get(self._tree, treeloc)['font'] = bold
for treeloc in self._parser.frontier()[1:]:
self._get(self._tree, treeloc)['color'] = '#008080'
def _highlight_prodlist(self):
# Highlight the productions that can be expanded.
# Boy, too bad tkinter doesn't implement Listbox.itemconfig;
# that would be pretty useful here.
self._prodlist.delete(0, 'end')
expandable = self._parser.expandable_productions()
untried = self._parser.untried_expandable_productions()
productions = self._productions
for index in range(len(productions)):
if productions[index] in expandable:
if productions[index] in untried:
self._prodlist.insert(index, ' %s' % productions[index])
else:
self._prodlist.insert(index, ' %s (TRIED)' %
productions[index])
self._prodlist.selection_set(index)
else:
self._prodlist.insert(index, ' %s' % productions[index])
def _position_text(self):
# Line up the text widgets that are matched against the tree
numwords = len(self._sent)
num_matched = numwords - len(self._parser.remaining_text())
leaves = self._tree_leaves()[:num_matched]
xmax = self._tree.bbox()[0]
for i in range(0, len(leaves)):
widget = self._textwidgets[i]
leaf = leaves[i]
widget['color'] = '#006040'
leaf['color'] = '#006040'
widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
xmax = widget.bbox()[2] + 10
# Line up the text widgets that are not matched against the tree.
for i in range(len(leaves), numwords):
widget = self._textwidgets[i]
widget['color'] = '#a0a0a0'
widget.move(xmax - widget.bbox()[0], 0)
xmax = widget.bbox()[2] + 10
# If we have a complete parse, make everything green :)
if self._parser.currently_complete():
for twidget in self._textwidgets:
twidget['color'] = '#00a000'
# Move the matched leaves down to the text.
for i in range(0, len(leaves)):
widget = self._textwidgets[i]
示例3: second_window
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
def second_window(root, info):
def next_step():
idxs = lbox.curselection()
for blogger in idxs:
name = bloggers()[blogger]
if name not in info['bloggers']:
info['bloggers'].append(name)
if 'Blogs' in info['platforms']:
blog_posts(root, info)
else:
third_window(root, info)
def cantfind(info=info):
idxs = lbox.curselection()
for blogger in idxs:
name = bloggers()[blogger]
if name not in info['bloggers']:
info['bloggers'].append(name)
add_blogger(info=info)
def active_next(*args):
send.state(['!disabled', 'active'])
def back():
idxs = lbox.curselection()
for blogger in idxs:
name = bloggers()[blogger]
if name not in info['bloggers']:
info['bloggers'].append(name)
first_window(root, info=info)
c = ttk.Frame(root, padding=(5, 0, 0, 0))
c.grid(column=0, row=0, sticky=(N, W, E, S))
background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/moon.gif' % home)
background_label = tkinter.Label(c, image=background_image)
background_label.image = background_image
background_label.place(x=0, y=0, relwidth=1, relheight=1)
root.grid_columnconfigure(0, weight=3)
root.grid_rowconfigure(0, weight=3)
lbox = Listbox(c, selectmode=MULTIPLE)
lbox.grid(column=0, row=1, rowspan=11, columnspan=7, sticky=(
N, W, S), padx=(10, 10), pady=(1, 1), ipadx=75)
yscroll = ttk.Scrollbar(command=lbox.yview, orient=VERTICAL)
yscroll.grid(row=0, column=0, padx=(0, 10), sticky=(N, W, S))
lbox.configure(yscrollcommand=yscroll.set)
for blogger in bloggers():
lbox.insert(END, blogger)
lbox.bind("<<ListboxSelect>>")
lbox.yview_scroll(40, 'units')
cantfind = ttk.Button(c, text='Add new bloggers', command=cantfind)
cantfind.grid(column=4, row=1, padx=(10, 0), sticky=(N, S, E, W), pady=(20, 10))
send = ttk.Button(c, text='Next', command=next_step, default='active', state='disabled')
send.grid(column=6, row=11, sticky=E, pady=20, padx=(2, 20))
close = ttk.Button(c, text='Back', command=back, default='active')
close.grid(column=5, row=11, sticky=S + E, pady=20, padx=2)
lbox.bind('<<ListboxSelect>>', active_next)
if info['bloggers']:
for blogger in info['bloggers']:
i = bloggers().index(blogger)
lbox.selection_set(i)
active_next()
for i in range(len(bloggers()), 2):
lbox.itemconfigure(i, background='#f0f0ff')
c.grid_columnconfigure(0, weight=1)
c.grid_rowconfigure(5, weight=1)
root.title('2/5 Select bloggers')
root.geometry('680x550+300+40')
示例4: ShiftReduceApp
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
stackx = max(stackx, self._stacklabel.width()+25)
rlabelwidth = self._rtextlabel.width()+10
if stackx >= cx2-max(rtextwidth, rlabelwidth):
cx2 = stackx + max(rtextwidth, rlabelwidth)
for rtextwidget in self._rtextwidgets:
rtextwidget.move(4+cx2-rtextwidth, 0)
self._rtextlabel.move(cx2-self._rtextlabel.bbox()[2]-5, 0)
midx = (stackx + cx2-max(rtextwidth, rlabelwidth))/2
self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
(x1, y1, x2, y2) = self._stacklabel.bbox()
# Set up binding to allow them to shift a token by dragging it.
if len(self._rtextwidgets) > 0:
def drag_shift(widget, midx=midx, self=self):
if widget.bbox()[0] < midx: self.shift()
else: self._redraw()
self._rtextwidgets[0].bind_drag(drag_shift)
self._rtextwidgets[0].bind_click(self.shift)
# Draw the stack top.
self._highlight_productions()
def _draw_stack_top(self, widget):
# hack..
midx = widget.bbox()[2]+50
self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
def _highlight_productions(self):
# Highlight the productions that can be reduced.
self._prodlist.selection_clear(0, 'end')
for prod in self._parser.reducible_productions():
index = self._productions.index(prod)
self._prodlist.selection_set(index)
#########################################
## Button Callbacks
#########################################
def destroy(self, *e):
if self._top is None: return
self._top.destroy()
self._top = None
def reset(self, *e):
self._parser.initialize(self._sent)
self._lastoper1['text'] = 'Reset App'
self._lastoper2['text'] = ''
self._redraw()
def step(self, *e):
if self.reduce(): return True
elif self.shift(): return True
else:
if list(self._parser.parses()):
self._lastoper1['text'] = 'Finished:'
self._lastoper2['text'] = 'Success'
else:
self._lastoper1['text'] = 'Finished:'
self._lastoper2['text'] = 'Failure'
def shift(self, *e):
if self._animating_lock: return
if self._parser.shift():
tok = self._parser.stack()[-1]
self._lastoper1['text'] = 'Shift:'
示例5: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
def _canvas_mouse_moved(self, event):
if self._is_drawing_polygon:
x, y = self._canvas.window_to_canvas_coords(event.x, event.y)
self._current_layer.get_polygon_at(-1).get_vertex_at(-1)\
.set_coords(x, y)
self._canvas.notify_polygon_change(self._current_layer
.get_polygon_count()-1)
def _layer_change(self, event):
selection = self._layer_list.curselection()
if len(selection) > 0 and self._scene:
layer = self._scene.get_layer_at(selection[0])
if layer:
self._is_drawing_polygon = False
self._current_layer = layer
self._canvas.notify_new_layer(self._current_layer)
def _set_scene(self, scene: Scene) -> bool:
if scene.get_layer_count() <= 0:
messagebox.showerror("Error!", "Scene has no layers!")
return False
self._scene = scene
# Prepare canvas
# TODO Extra 10px padding for canvas
width, height = self._scene.get_size()
self._canvas.config(scrollregion=(0, 0, width, height))
# Empty listbox, fill it, select first entry
self._layer_list.delete(0, self._layer_list.size()-1)
for i in range(0, self._scene.get_layer_count()):
self._layer_list.insert(i, self._scene.get_layer_at(i).get_name())
self._layer_list.selection_set(0)
self._layer_list.event_generate("<<ListboxSelect>>")
return True
def _set_current_path(self, path):
self._current_path = path
if path:
self._tk.title(path + " - Layered Polygons")
else:
self._tk.title("Untitled - Layered Polygons")
def _new_scene(self):
path = filedialog.askopenfilename(defaultextension=".ora",
filetypes=[("OpenRaster files",
".ora")])
if not path:
return
scene = ora.read(path)
if not scene:
messagebox.showerror("Error!", "File could not be opened!")
return
if self._set_scene(scene):
self._set_current_path(None)
def _open_scene(self):
path = filedialog.askopenfilename(defaultextension=".lp",
filetypes=[("Layered polygons"
" files", ".lp")])
if not path:
return
示例6: Add_Recipe_Modal
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
class Add_Recipe_Modal(Modal):
def __init__(self, parent=None, title="Add Recipe"):
self.shorts = []
self.amounts = None
self.ingredients = None
Modal.__init__(self, parent, title, geometry="375x410" if system() == "Windows" else "375x350")
def initialize(self):
amount_label = Label(self, width=8, text="Amount")
amount_label.grid(row=0, column=0)
ingredients_label = Label(self, width=35, text="Item Name")
ingredients_label.grid(row=0, column=1)
self.amounts_list = Listbox(self, width=8, selectmode="single")
self.amounts_list.bind("<Double-Button-1>", self.edit)
self.amounts_list.grid(row=1, column=0, sticky="E")
self.ingredients_list = Listbox(self, width=35, selectmode="single")
self.ingredients_list.bind("<Double-Button-1>", self.edit)
self.ingredients_list.grid(row=1, column=1)
add_button = Button(self, width=7, text="Add", command=self.add)
self.bind("<Control-+>", self.add)
self.bind("<Insert>", self.add)
add_button.grid(row=2, column=1, sticky="E")
remove_button = Button(self, text="Remove", command=self.remove)
self.bind("<Delete>", self.remove)
remove_button.grid(row=2, column=0)
produces_label = Label(self, text="Produces: ")
produces_label.grid(row=3, column=0, sticky="W")
self.produces_box = Entry(self, width=5)
self.produces_box.insert(0, "1")
self.produces_box.grid(row=3, column=1, sticky="W")
machine_label = Label(self, text="Machine: ")
machine_label.grid(row=4, column=0, sticky="W")
self.machine_box = Entry(self)
self.machine_box.grid(row=4, column=1, sticky="EW")
info_label = Label(self, text="Extra Info: ")
info_label.grid(row=5, column=0, sticky="W")
self.info_box = Entry(self)
self.info_box.grid(row=5, column=1, sticky="EW")
cancel_button = Button(self, text="Cancel", width=7, command=self.cancel)
self.bind("<Escape>", self.cancel)
cancel_button.grid(row=6, column=0, pady=10)
ok_button = Button(self, text="OK", width=7, command=self.ok)
self.bind("<Return>", self.ok)
ok_button.grid(row=6, column=1, pady=10, sticky="E")
self.bind("<<ListboxSelect>>", self.sync)
def sync(self, event):
if event.widget is self.amounts_list and len(self.amounts_list.curselection()) != 0:
self.ingredients_list.selection_set(self.amounts_list.curselection()[0])
def add(self, event=None):
short, name, amount = Add_Ingredient_Modal().show()
if short is not None and name is not None and amount is not None:
if name not in self.ingredients_list.get(0, "end"):
self.ingredients_list.insert("end", name)
self.amounts_list.insert("end", amount)
self.shorts.append(short)
def edit(self, event=None):
if len(self.ingredients_list.curselection()) != 0:
index = self.ingredients_list.curselection()[0]
current_short = self.shorts[index]
current_name = self.ingredients_list.get(index)
current_amount = self.amounts_list.get(index)
new_short, new_name, new_amount = Edit_Ingredient_Modal().show(current_short, current_name, current_amount)
if new_short is not None and new_name is not None and new_amount is not None:
self.amounts_list.delete(index)
self.ingredients_list.delete(index)
self.amounts_list.insert(index, new_amount)
self.ingredients_list.insert(index, new_name)
self.shorts[index] = new_short
def remove(self, event=None):
if len(self.ingredients_list.curselection()) != 0:
slct = int(self.ingredients_list.curselection()[0])
self.ingredients_list.delete(slct)
self.amounts_list.delete(slct)
del(self.shorts[slct])
def ok(self, event=None):
if len(self.ingredients_list.get(0)) != 0 and self.produces_box is not None and self.produces_box.get().isdigit():
self.produces = int(self.produces_box.get())
self.amounts = self.amounts_list.get(0, last="end")
self.ingredients = self.ingredients_list.get(0, last="end")
self.machine = self.machine_box.get()
#.........这里部分代码省略.........
示例7: ListboxVidget
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
raise ListboxVidget.CircularCallError()
# If the listbox is not changing.
# Set changing flag on
self._is_changing = True
# Get old active index
old_indexcur = self._indexcur
# Set resetting flag on if new and old indexes are equal
self._is_resetting = (index == old_indexcur)
# If notify events
if notify:
# Notify pre-change event
self.handler_notify(self.ITEMCUR_CHANGE_SOON, notify_arg)
# If old active index is valid
if self.index_is_valid(old_indexcur):
# Set old active item's background color to normal color
self._listbox.itemconfig(old_indexcur, background=self._normal_bg)
# Set old active item's foreground color to normal color
self._listbox.itemconfig(old_indexcur, foreground=self._normal_fg)
# Cache new active index
self._indexcur = index
# Clear listbox widget's selection
self._listbox.selection_clear(0, END)
# Set listbox widget's selection
self._listbox.selection_set(index)
# Set listbox widget's activated index
self._listbox.activate(index)
# If new active index is valid
if index != -1:
# Set new active item's background color to active color
self._listbox.itemconfig(index, background=self._active_bg)
# Set new active item's foreground color to active color
self._listbox.itemconfig(index, foreground=self._active_fg)
# If set focus
if focus:
# Set focus on the listbox widget
self._listbox.focus_set()
# If new active index is valid
if index != -1:
# Make the active item visible
self._listbox.see(index)
# If notify events
if notify:
# Notify post-change event
self.handler_notify(self.ITEMCUR_CHANGE_DONE, notify_arg)
# Set resetting flag off
self._is_resetting = False
# Set changing flag off
self._is_changing = False
示例8: LucteriosMainForm
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
extra_urls = lct_glob.get_extra_urls()
if len(extra_urls) > 0:
self.module_txt.insert(END, "\n")
self.module_txt.insert(END, ugettext("Pypi servers\n"))
for extra_url in extra_urls:
self.module_txt.insert(END, "\t%s\n" % extra_url)
self.module_txt.config(state=DISABLED)
self.has_checked = True
self.after(1000, lambda: Thread(target=self.check).start())
def _refresh_instance_list(self):
self.instance_list.delete(0, END)
luct_glo = LucteriosGlobal()
instance_list = luct_glo.listing()
for item in instance_list:
self.instance_list.insert(END, item)
if item not in self.running_instance.keys():
self.running_instance[item] = None
instance_names = list(self.running_instance.keys())
for old_item in instance_names:
if old_item not in instance_list:
if self.running_instance[old_item] is not None:
self.running_instance[old_item].stop()
del self.running_instance[old_item]
def set_select_instance_name(self, instance_name):
cur_sel = 0
for sel_iter in range(self.instance_list.size()):
if self.instance_list.get(sel_iter) == instance_name:
cur_sel = sel_iter
break
self.instance_list.selection_set(cur_sel)
self.select_instance(None)
def get_selected_instance_name(self):
if len(self.instance_list.curselection()) > 0:
return self.instance_list.get(int(self.instance_list.curselection()[0]))
else:
return ""
def set_ugrade_state(self, must_upgrade):
if must_upgrade:
self.btnupgrade.config(state=NORMAL)
self.btnupgrade["text"] = ugettext("Upgrade needs")
else:
self.btnupgrade["text"] = ugettext("No upgrade")
self.btnupgrade.config(state=DISABLED)
def check(self):
must_upgrade = False
try:
lct_glob = LucteriosGlobal()
_, must_upgrade = lct_glob.check()
finally:
self.after(300, self.set_ugrade_state, must_upgrade)
@ThreadRun
def upgrade(self):
self.btnupgrade.config(state=DISABLED)
self.instance_list.config(state=DISABLED)
try:
from logging import getLogger
admin_path = import_module(
"lucterios.install.lucterios_admin").__file__
示例9: InstanceEditor
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3)
Label(self.frm_general, text=ugettext("Password")).grid(
row=5, column=0, sticky=(N, W), padx=5, pady=3)
self.password = Entry(self.frm_general, show="*")
self.password.grid(
row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3)
def typedb_selection(self, event):
visible = list(self.typedb[VALUES]).index(self.typedb.get()) != 0
for child_cmp in self.frm_database.winfo_children()[2:]:
if visible:
child_cmp.config(state=NORMAL)
else:
child_cmp.config(state=DISABLED)
def appli_selection(self, event):
if self.applis.get() != '':
appli_id = list(self.applis[VALUES]).index(self.applis.get())
luct_glo = LucteriosGlobal()
current_inst_names = luct_glo.listing()
appli_root_name = self.mod_applis[appli_id][0].split('.')[-1]
default_name_idx = 1
while appli_root_name + six.text_type(default_name_idx) in current_inst_names:
default_name_idx += 1
self.name.delete(0, END)
self.name.insert(
0, appli_root_name + six.text_type(default_name_idx))
mod_depended = self.mod_applis[appli_id][2]
self.modules.select_clear(0, self.modules.size())
for mod_idx in range(len(self.module_data)):
current_mod = self.module_data[mod_idx]
if current_mod in mod_depended:
self.modules.selection_set(mod_idx)
def mode_selection(self, event):
visible = list(self.mode[VALUES]).index(self.mode.get()) != 2
for child_cmp in self.frm_general.winfo_children()[-2:]:
if visible:
child_cmp.config(state=NORMAL)
else:
child_cmp.config(state=DISABLED)
def apply(self):
from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang
if self.name.get() == '':
showerror(ugettext("Instance editor"), ugettext("Name empty!"))
return
if self.applis.get() == '':
showerror(ugettext("Instance editor"), ugettext("No application!"))
return
db_param = "%s:name=%s,user=%s,password=%s" % (
self.typedb.get(), self.namedb.get(), self.userdb.get(), self.pwddb.get())
security = "MODE=%s" % list(
self.mode[VALUES]).index(self.mode.get())
if self.password.get() != '':
security += ",PASSWORD=%s" % self.password.get()
module_list = [
self.module_data[int(item)] for item in self.modules.curselection()]
appli_id = list(self.applis[VALUES]).index(self.applis.get())
current_lang = get_locale_lang()
for lang in DEFAULT_LANGUAGES:
if lang[1] == self.language.get():
current_lang = lang[0]
self.result = (self.name.get(), self.mod_applis[appli_id][
0], ",".join(module_list), security, db_param, current_lang)
示例10: LogUI
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
if index < 0:
cond = JoinSearchCondition(("", ""))
tofilename = ""
else:
condtuple = self._getselectedfile().joincondtuples[index]
cond = condtuple[0]
tofilename = condtuple[1]
window = Toplevel(self)
title = Label(window, text="New Search Condition")
title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N)
filenamelabel = Label(window, text="Target Field Name: ")
filenamelabel.grid(row=1, column=0, padx=5, pady=5, sticky=W)
filevar = StringVar(window)
filenameinput = Combobox(window, textvariable=filevar, values=self.filelist.get(0, END), width=30)
filenameinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W)
fromfieldlabel = Label(window, text="Field in From File: ")
fromfieldlabel.grid(row=3, column=0, padx=5, pady=5, sticky=W)
fromfields = csvhandler.getfields(self._getselectedfile().filename)
fromfieldvar = StringVar(window)
fieldinput = Combobox(window, textvariable=fromfieldvar, values=fromfields, width=20)
fieldinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W)
tofieldlabel = Label(window, text="Field in Target File: ")
tofieldlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W)
tofields = []
tofieldvar = StringVar(window)
tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20)
tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W)
def updatetofieldinput(evt):
if filevar.get() is not None and len(filevar.get()) > 0:
tofields = csvhandler.getfields(filevar.get())
window.grid_slaves(4, 1)[0].grid_forget()
tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20)
tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W)
filenameinput.bind('<<ComboboxSelected>>', updatetofieldinput)
# init value
filevar.set(tofilename)
fromfieldvar.set(cond.fieldtuple[0])
updatetofieldinput(None)
tofieldvar.set(cond.fieldtuple[1])
def _newcond():
'''create new condition
'''
cond = JoinSearchCondition((fromfieldvar.get(), tofieldvar.get()))
tofilename = filevar.get()
selectedfile = self._getselectedfile()
if index < 0:
selectedfile.joincondtuples.append((cond, tofilename))
else:
del selectedfile.joincondtuples[index]
selectedfile.joincondtuples[index:index] = [(cond, tofilename)]
self._inflatejoincondlist(selectedfile.joincondtuples)
window.destroy()
okbtn = Button(window, text="Confirm", width=7, command=_newcond)
okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5)
clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy())
clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=W, padx=5, pady=5)
def _getselectedfile(self):
if self._getselectedfileindex() < 0:
return None
return self.filemodels[self._getselectedfileindex()]
def _getselectedfileindex(self):
return self.selectedfileindex
def _setselectedfileindex(self, index):
self.selectedfileindex = index
if index >= 0:
self.filelist.selection_set(index)
def _getselectedsearchcondindex(self):
if len(self.searchcondlist.curselection()) > 0:
return self.searchcondlist.curselection()[0]
return -1
def _getselectedjoincondindex(self):
if len(self.joincondlist.curselection()) > 0:
return self.joincondlist.curselection()[0]
return -1
示例11: DrtGlueDemo
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
#.........这里部分代码省略.........
Message(message=ABOUT, title=TITLE).show()
except:
ShowText(self._top, TITLE, ABOUT)
def postscript(self, *e):
self._autostep = 0
self._cframe.print_to_file()
def mainloop(self, *args, **kwargs):
"""
Enter the Tkinter mainloop. This function must be called if
this demo is created from a non-interactive program (e.g.
from a secript); otherwise, the demo will close as soon as
the script completes.
"""
if in_idle():
return
self._top.mainloop(*args, **kwargs)
def resize(self, size=None):
if size is not None:
self._size.set(size)
size = self._size.get()
self._font.configure(size=-(abs(size)))
self._boldfont.configure(size=-(abs(size)))
self._sysfont.configure(size=-(abs(size)))
self._bigfont.configure(size=-(abs(size + 2)))
self._redraw()
def _toggle_remove_duplicates(self):
self._glue.remove_duplicates = not self._glue.remove_duplicates
self._exampleList.selection_clear(0, "end")
self._readings = []
self._populate_readingListbox()
self._readingCache = [None for ex in self._examples]
self._curExample = -1
self._error = None
self._drs = None
self._redraw()
def _exampleList_select(self, event):
selection = self._exampleList.curselection()
if len(selection) != 1:
return
self._exampleList_store_selection(int(selection[0]))
def _exampleList_store_selection(self, index):
self._curExample = index
example = self._examples[index]
self._exampleList.selection_clear(0, "end")
if example:
cache = self._readingCache[index]
if cache:
if isinstance(cache, list):
self._readings = cache
self._error = None
else:
self._readings = []
self._error = cache
else:
try:
self._readings = self._glue.parse_to_meaning(example)
self._error = None
self._readingCache[index] = self._readings
except Exception as e:
self._readings = []
self._error = DrtVariableExpression(Variable("Error: " + str(e)))
self._readingCache[index] = self._error
# add a star to the end of the example
self._exampleList.delete(index)
self._exampleList.insert(index, (" %s *" % example))
self._exampleList.config(height=min(len(self._examples), 25), width=40)
self._populate_readingListbox()
self._exampleList.selection_set(index)
self._drs = None
self._redraw()
def _readingList_select(self, event):
selection = self._readingList.curselection()
if len(selection) != 1:
return
self._readingList_store_selection(int(selection[0]))
def _readingList_store_selection(self, index):
reading = self._readings[index]
self._readingList.selection_clear(0, "end")
if reading:
self._readingList.selection_set(index)
self._drs = reading.simplify().normalize().resolve_anaphora()
self._redraw()
示例12: AutocompleteEntry
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
class AutocompleteEntry(Entry):
def __init__(self, *args, **kwargs):
Entry.__init__(self, width=100, *args, **kwargs)
self.focus_set()
self.pack()
self.var = self["textvariable"]
if self.var == '':
self.var = self["textvariable"] = StringVar()
self.var.trace('w', self.changed)
self.bind("<Right>", self.selection)
self.bind("<Up>", self.up)
self.bind("<Down>", self.down)
self.bind("<Return>", self.enter)
self.lb_up = False
self.lb = None
def enter(self, event):
print(event)
def changed(self, name, index, mode):
if self.var.get() == '':
if self.lb:
self.lb.destroy()
self.lb_up = False
else:
words = self.comparison()
if words:
if not self.lb_up:
self.lb = Listbox(master=root, width=100)
self.lb.bind("<Double-Button-1>", self.selection)
self.lb.bind("<Right>", self.selection)
self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
self.lb_up = True
self.lb.delete(0, END)
for w in words:
self.lb.insert(END,w)
else:
if self.lb_up:
self.lb.destroy()
self.lb_up = False
def selection(self, _):
if self.lb_up:
self.var.set(self.lb.get(ACTIVE))
self.lb.destroy()
self.lb_up = False
self.icursor(END)
def up(self, _):
if self.lb_up:
if self.lb.curselection() == ():
index = '0'
else:
index = self.lb.curselection()[0]
if index != '0':
self.lb.selection_clear(first=index)
index = str(int(index)-1)
self.lb.selection_set(first=index)
self.lb.activate(index)
def down(self, _):
if self.lb_up:
if self.lb.curselection() == ():
index = '0'
else:
index = self.lb.curselection()[0]
if index != END:
self.lb.selection_clear(first=index)
index = str(int(index)+1)
self.lb.selection_set(first=index)
self.lb.activate(index)
def comparison(self):
q = self.var.get()
q = str(q.decode('utf8'))
for hit in searcher.search(qp.parse(q), limit=50):
if hit['author']:
yield '%s. "%s"' % (hit['author'], hit['title'])
else:
yield hit['title']
示例13: TextSelect
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import selection_set [as 别名]
class TextSelect(Frame):
def __init__(self, client, anchor, items, destroyAnchor=False):
"""
Args:
client: [SelectionClient] The window that text is returned to.
anchor: A window that the text selection popup is created
relative to.
items: [str], items to display in the listbox.
destroyAnchor: [bool] if true, destroy the anchor after
positioning the window.
"""
self.top = Toplevel()
self.anchor = anchor
self.top.overrideredirect(1)
self.top.wm_geometry('+%s+%s' % (anchor.winfo_rootx() + anchor.winfo_x(),
anchor.winfo_rooty() + anchor.winfo_y()
)
)
super(TextSelect, self).__init__(self.top)
self.entry = Entry(self)
self.client = client
self.items = items
self.place(x = 0.5, y = 0.5, height = 100, width = 100)
self.entry.bind('<Return>', self.close)
self.entry.bind('<KeyPress>', self.filter)
self.entry.bind('<Escape>', self.abort)
self.entry.bind('<Up>', self.up)
self.entry.bind('<Down>', self.down)
self.entry.pack()
# Create the list of items.
self.list = Listbox(self)
for item in self.items:
self.list.insert('end', item)
self.list.pack()
self.grid()
self.entry.focus()
# Reposition the select button against the anchor. We defer this
# until after idle so that the anchor has a chance to get rendered.
def reposition(*args):
self.top.wm_geometry('+%s+%s' % (
anchor.winfo_rootx(),
anchor.winfo_rooty())
)
if destroyAnchor:
anchor.destroy()
self.after_idle(reposition)
def close(self, event):
sel = self.list.curselection()
if sel:
item = self.list.get(sel[0])
else:
item = self.entry.get()
# Note that the order of this appears to be significant: destroying
# before selecting leaves the focus in a weird state.
self.client.selected(item)
self.top.destroy()
return 'braek'
def abort(self, event):
self.top.destroy()
self.client.aborted()
return 'break'
def up(self, event):
sel = self.list.curselection()
if not sel:
self.list.selection_set(0)
return 'break'
sel = sel[0]
print('sel is %s size is %s' % (sel, self.list.size()))
if sel > 0:
print('setting selection to %s' % sel)
self.list.selection_clear(sel)
self.list.selection_set(sel - 1)
self.list.see(sel)
return 'break'
def down(self, event):
sel = self.list.curselection()
if not sel:
self.list.selection_set(0)
return 'break'
sel = sel[0]
print('sel is %s size is %s' % (sel, self.list.size()))
if sel < self.list.size() - 1:
print('setting selection to %s' % (sel + 1))
self.list.selection_clear(sel)
self.list.selection_set(sel + 1)
self.list.see(sel)
return 'break'
def filter(self, event):
"""Filter the listbox based on the contents of the entryfield."""
#.........这里部分代码省略.........