本文整理汇总了Python中tkinter.Listbox.curselection方法的典型用法代码示例。如果您正苦于以下问题:Python Listbox.curselection方法的具体用法?Python Listbox.curselection怎么用?Python Listbox.curselection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Listbox
的用法示例。
在下文中一共展示了Listbox.curselection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: insert_list
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
def insert_list(self, items):
frame = self.frame
frame.pack(fill="y")
lb = Listbox(frame, selectmode="multiple")
for i in items:
lb.insert("end", i)
lb.pack()
self.ok_cancel_buttons(call=lambda : self.del_items(lb.curselection()))
示例2: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
class MiniWindow:
def __init__(self,root,list):
self.list = list
self.mini = Toplevel(root)
self.mini.wm_title("Matches")
print (root.winfo_screenwidth())
self.mini.geometry("%dx%d+%d+%d" %(500,200,root.winfo_x()+root.winfo_width(),root.winfo_y()))
self.filelist = Listbox(self.mini)
for item in self.list:
self.filelist.insert('end',str(item))
self.filelist.bind("<<ListboxSelect>>",self.onClick)
self.filelist.pack(fill="both")
def onClick(self,event):
print(self.filelist.curselection())
index = int(self.filelist.curselection()[0])
link = self.list[index]
filedir = os.path.dirname(link)
if os.name == 'nt':
os.startfile(filedir)
elif os.name == 'posix':
subprocess.Popen(["xdg-open",filedir])
示例3: LabeledListBox
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [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)
示例4: ListboxVidget
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
# If have active indexes
if indexcurs:
# Return the first active index
return indexcurs[0]
# If no active indexes
else:
# If raise error
if raise_error:
# Raise error
raise IndexError(-1)
# If not raise error
else:
# Return -1
return -1
def _indexcurs(self, internal=False):
"""
Get active indexes list.
2N6OR
@param internal: Whether use listbox widget's selected indexes, instead
of cached active index.
Notice listbox widget has no selected indexes if it has no focus.
Notice using cached active index only supports single-selection mode,
which means the result list has at most one index.
@return: Active indexes list.
"""
# If use listbox widget's selected indexes
if internal:
# Return listbox widget's selected indexes list
return [int(x) for x in self._listbox.curselection()]
# If not use listbox widget's selected indexes
else:
# If cached active index is valid
if self.index_is_valid(self._indexcur):
# Return a list with the cached active index
return [self._indexcur]
# If cached active index is not valid
else:
# Return empty list
return []
def indexcur_set(
self,
index,
focus=False,
notify=True,
notify_arg=None,
):
"""
Set active index.
@param index: The index to set.
@param focus: Whether set focus on the listbox widget.
@param notify: Whether notify pre-change and post-change events.
@param notify_arg: Event argument.
@return: None.
示例5: SelectDeviceFrame
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
class SelectDeviceFrame(CopilotInnerFrame):
def __init__(self, master, config, state):
super(SelectDeviceFrame, self).__init__(master, config)
self._state = state
if self._state.action == 'copy':
self._frame_lbl['text'] = 'Copy To Device'
elif self._state.action == 'delete':
self._frame_lbl['text'] = 'Delete From Device'
self._next_btn['command'] = self._next_cmd
self._dev_list = Listbox(self._master, font=self._config.item_font)
self._dev_list.grid(row=1, column=0, columnspan=3, sticky='nsew')
self._dev_list.configure(yscrollcommand=self._sb.set)
self._sb['command'] = self._dev_list.yview
self._refresh_drives()
def _next_cmd(self):
if len(self._dev_list.curselection()) > 0:
item_idx = int(self._dev_list.curselection()[0])
self._state.to_device = self._parts[item_idx]
if self._state.action == 'copy':
self._new_state_window(DeviceToFrame, self._state)
elif self._state.action == 'delete':
self._new_state_window(CopyFileFrame, self._state)
def _refresh_drives(self):
self._parts = []
for drive in usb_drives():
for part in drive.partitions():
drive_opt = DriveOption(drive, part)
self._parts.append(drive_opt)
self._dev_list.insert('end', drive_opt)
示例6: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
class ListChooserDialog:
def __init__(self, parent, listEntries, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False):
"""
NOTE: do not call this constructor directly. Use the ListChooserDialog.showDialog function instead.
"""
self.forceFolderOnlyChoosing = forceFolderOnlyChoosing
self.top = tkinter.Toplevel(parent)
defaultPadding = {"padx":20, "pady":10}
# Set a description for this dialog (eg "Please choose a game to mod"
tkinter.Label(self.top, text=guiPrompt).pack()
# Define the main listbox to hold the choices given by the 'listEntries' parameter
listboxFrame = tkinter.Frame(self.top)
# Define a scrollbar and a listbox. The yscrollcommand is so that the listbox can control the scrollbar
scrollbar = tkinter.Scrollbar(listboxFrame, orient=tkinter.VERTICAL)
self.listbox = Listbox(listboxFrame, selectmode=tkinter.BROWSE, yscrollcommand=scrollbar.set)
# Also configure the scrollbar to control the listbox, and pack it
scrollbar.config(command=self.listbox.yview)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
# Setting width to 0 forces auto-resize of listbox see: https://stackoverflow.com/a/26504193/848627
for item in listEntries:
self.listbox.insert(tkinter.END, item)
self.listbox.config(width=0)
self.listbox.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)
# Finally, pack the Frame so its contents are displayed on the dialog
listboxFrame.pack(**defaultPadding)
# If the user is allowed to choose a directory manually, add directory chooser button
if allowManualFolderSelection:
b2 = tkinter.Button(self.top, text="Choose Folder Manually", command=self.showDirectoryChooser)
b2.pack(**defaultPadding)
# Add an 'OK' button. When pressed, the dialog is closed
b = tkinter.Button(self.top, text="OK", command=self.ok)
b.pack(**defaultPadding)
# This variable stores the returned value from the dialog
self.result = None
def showDirectoryChooser(self):
if IS_MAC and not self.forceFolderOnlyChoosing:
self.result = filedialog.askopenfilename(filetypes=[(None, "com.apple.application")])
else:
self.result = filedialog.askdirectory()
self.top.destroy()
def ok(self):
"""
This function is called when the 'OK' button is pressed. It retrieves the value of the currently selected item,
then closes the dialog
:return:
"""
selected_value = None
if len(self.listbox.curselection()) > 0:
selected_index = self.listbox.curselection()[0]
selected_value = self.listbox.get(selected_index)
self.result = selected_value
self.top.destroy()
@staticmethod
def showDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False):
"""
Static helper function to show dialog and get a return value. Arguments are the same as constructor
:param rootGUIWindow: the parent tkinter object of the dialog (can be root window)
:param choiceList: a list of strings that the user is to choose from
:param guiPrompt: the description that will be shown on the dialog
:param allowManualFolderSelection: if true, user is allowed to select a folder manually.
:return: returns the value the user selected (string), or None if none available
"""
d = ListChooserDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing)
rootGUIWindow.wait_window(d.top)
return d.result
示例7: ProblemBrowser
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
class ProblemBrowser(object):
def __init__(self):
self.action = None
self.root = root = Tk()
root.title('Never gonna fold you up')
root.protocol("WM_DELETE_WINDOW", self.close)
root.pack_propagate(True)
scrollbar = Scrollbar(root, orient=tkinter.VERTICAL)
self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set)
self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
scrollbar.config(command=self.problem_list.yview)
scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y)
self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas())
self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas())
button_frame = Frame(root)
button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT)
# Reposition the figure so it's center of mass is at 0.5, 0.5
v = IntVar()
self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas())
self.center_cb.var = v
self.center_cb.pack(side=tkinter.TOP)
# Use meshes.reconstruct_facets instead of polygon/hole logic.
v = IntVar()
self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas())
self.reconstruct_cb.var = v
self.reconstruct_cb.pack(side=tkinter.TOP)
self.populate_problems()
self.current_problem_name = None
self.current_problem = None
def populate_problems(self):
self.problem_list.delete(0, tkinter.END)
for file in sorted((get_root() / 'problems').iterdir()):
self.problem_list.insert(tkinter.END, file.stem)
def populate_problem_canvas(self):
sel = self.problem_list.curselection()
if not sel: return
assert len(sel) == 1
name = self.problem_list.get(sel[0])
if name != self.current_problem_name:
self.current_problem_name = name
self.current_problem = load_problem(name)
if self.current_problem:
p = self.current_problem
if self.center_cb.var.get():
p = center_problem(p)
if self.reconstruct_cb.var.get():
facets = meshes.reconstruct_facets(p)
facets = meshes.keep_real_facets(facets, p)
skeleton = [e for f in facets for e in edges_of_a_facet(f)]
p = Problem(facets, skeleton)
draw_problem(self.problem_canvas, p)
def run(self):
self.root.mainloop()
def close(self):
if self.root:
self.root.destroy()
self.root = None
示例8: LucteriosMainForm
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
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__
proc = Popen(
[sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE)
value = proc.communicate()[0]
try:
示例9: InstanceEditor
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
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)
self.destroy()
def _load_current_data(self, instance_name):
from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang
lct_inst = LucteriosInstance(instance_name)
lct_inst.read()
self.name.delete(0, END)
self.name.insert(0, lct_inst.name)
self.name.config(state=DISABLED)
applis_id = 0
for appli_iter in range(len(self.mod_applis)):
if self.mod_applis[appli_iter][0] == lct_inst.appli_name:
applis_id = appli_iter
break
self.applis.current(applis_id)
if lct_inst.extra['']['mode'] is not None:
self.mode.current(lct_inst.extra['']['mode'][0])
else:
self.mode.current(2)
self.mode_selection(None)
typedb_index = 0
for typedb_idx in range(len(self.typedb[VALUES])):
if self.typedb[VALUES][typedb_idx].lower() == lct_inst.database[0].lower():
typedb_index = typedb_idx
break
示例10: ShiftReduceApp
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
def set_grammar(self, grammar):
self._parser.set_grammar(grammar)
self._productions = list(grammar.productions())
self._prodlist.delete(0, 'end')
for production in self._productions:
self._prodlist.insert('end', (' %s' % production))
def edit_sentence(self, *e):
sentence = " ".join(self._sent)
title = 'Edit Text'
instr = 'Enter a new sentence to parse.'
EntryDialog(self._top, sentence, instr, self.set_sentence, title)
def set_sentence(self, sent):
self._sent = sent.split() #[XX] use tagged?
self.reset()
#########################################
## Reduce Production Selection
#########################################
def _toggle_grammar(self, *e):
if self._show_grammar.get():
self._prodframe.pack(fill='both', side='left', padx=2,
after=self._feedbackframe)
self._lastoper1['text'] = 'Show Grammar'
else:
self._prodframe.pack_forget()
self._lastoper1['text'] = 'Hide Grammar'
self._lastoper2['text'] = ''
def _prodlist_select(self, event):
selection = self._prodlist.curselection()
if len(selection) != 1: return
index = int(selection[0])
production = self._parser.reduce(self._productions[index])
if production:
self._lastoper1['text'] = 'Reduce:'
self._lastoper2['text'] = '%s' % production
if self._animate.get():
self._animate_reduce()
else:
self._redraw()
else:
# Reset the production selections.
self._prodlist.selection_clear(0, 'end')
for prod in self._parser.reducible_productions():
index = self._productions.index(prod)
self._prodlist.selection_set(index)
def _popup_reduce(self, widget):
# Remove old commands.
productions = self._parser.reducible_productions()
if len(productions) == 0: return
self._reduce_menu.delete(0, 'end')
for production in productions:
self._reduce_menu.add_command(label=str(production),
command=self.reduce)
self._reduce_menu.post(self._canvas.winfo_pointerx(),
self._canvas.winfo_pointery())
#########################################
## Animations
#########################################
示例11: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
text="Messages by category",
variable=self.box,
value="Messages by category",
command=self.refresh_results_window,
)
msg = Radiobutton(
radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window
)
report.select()
report.grid(column=0, row=0, sticky=W)
rawMet.grid(column=1, row=0, sticky=W)
dup.grid(column=2, row=0, sticky=W)
msg.grid(column=3, row=0, sticky=E)
stat.grid(column=0, row=1, sticky=W)
msgCat.grid(column=1, row=1, sticky=W)
ext.grid(column=2, row=1, columnspan=2, sticky=W)
# dictionary for check boxes and associated error term
self.msg_type_dict = {
"I": lambda: self.information_box.get() == 1,
"C": lambda: self.convention_box.get() == 1,
"R": lambda: self.refactor_box.get() == 1,
"E": lambda: self.error_box.get() == 1,
"W": lambda: self.warning_box.get() == 1,
"F": lambda: self.fatal_box.get() == 1,
}
self.txtModule.focus_set()
def select_recent_file(self, event):
"""adds the selected file in the history listbox to the Module box"""
if not self.showhistory.size():
return
selected = self.showhistory.curselection()
item = self.showhistory.get(selected)
# update module
self.txtModule.delete(0, END)
self.txtModule.insert(0, item)
def refresh_msg_window(self):
"""refresh the message window with current output"""
# clear the window
self.lbMessages.delete(0, END)
for msg in self.msgs:
if self.msg_type_dict.get(msg[0])():
msg_str = self.convert_to_string(msg)
self.lbMessages.insert(END, msg_str)
fg_color = COLORS.get(msg_str[:3], "black")
self.lbMessages.itemconfigure(END, fg=fg_color)
def refresh_results_window(self):
"""refresh the results window with current output"""
# clear the window
self.results.delete(0, END)
try:
for res in self.tabs[self.box.get()]:
self.results.insert(END, res)
except:
pass
def convert_to_string(self, msg):
"""make a string representation of a message"""
if msg[2] != "":
return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4]
else:
return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4]
示例12: AutocompleteEntry
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [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 curselection [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."""
#.........这里部分代码省略.........
示例14: Add_Recipe_Modal
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [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()
#.........这里部分代码省略.........
示例15: DrtGlueDemo
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import curselection [as 别名]
#.........这里部分代码省略.........
parent.config(menu=menubar)
#########################################
## Main draw procedure
#########################################
def _redraw(self):
canvas = self._canvas
# Delete the old DRS, widgets, etc.
if self._drsWidget is not None:
self._drsWidget.clear()
if self._drs:
self._drsWidget = DrsWidget(self._canvas, self._drs)
self._drsWidget.draw()
if self._error:
self._drsWidget = DrsWidget(self._canvas, self._error)
self._drsWidget.draw()
#########################################
## Button Callbacks
#########################################
def destroy(self, *e):
self._autostep = 0
if self._top is None:
return
self._top.destroy()
self._top = None
def prev(self, *e):
selection = self._readingList.curselection()
readingListSize = self._readingList.size()
# there are readings
if readingListSize > 0:
# if one reading is currently selected
if len(selection) == 1:
index = int(selection[0])
# if it's on (or before) the first item
if index <= 0:
self._select_previous_example()
else:
self._readingList_store_selection(index - 1)
else:
# select its first reading
self._readingList_store_selection(readingListSize - 1)
else:
self._select_previous_example()
def _select_previous_example(self):
# if the current example is not the first example
if self._curExample > 0:
self._exampleList_store_selection(self._curExample - 1)
else:
# go to the last example
self._exampleList_store_selection(len(self._examples) - 1)
def next(self, *e):
selection = self._readingList.curselection()
readingListSize = self._readingList.size()