本文整理汇总了Python中tkinter.Listbox.get方法的典型用法代码示例。如果您正苦于以下问题:Python Listbox.get方法的具体用法?Python Listbox.get怎么用?Python Listbox.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Listbox
的用法示例。
在下文中一共展示了Listbox.get方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ShapesMenu
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
class ShapesMenu(object):
"""
"""
def __init__(self, master, line_collection):
try:
self.width_of_entry = len(line_collection[0])
except IndexError:
self.width_of_entry = 0
self.top = Toplevel(master)
self.current_lines_listbox = Listbox(self.top)
self.removed_lines_listbox = Listbox(self.top)
self.submit = Button(self.top, text = "Ok", command=self.submit)
self.remove_button = Button(self.top, text = "Remove", command=self.remove_line)
self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy)
self.top.bind("<Return>", func=self.submit)
self.current_lines = line_collection
self.removed_lines = []
self.ids_internal = []
self.ids = []
for index, line in enumerate(self.current_lines):
#removes the point data and converts the rest to strings
id = line[1]
if id not in self.ids_internal:
self.ids_internal.append(id)
self.ids.append(id)
line = [str(element) for element in line[1:]]
#put into the list
self.current_lines_listbox.insert(index, " ".join(line))
self.current_lines_listbox.grid(row=0, column=0, columnspan=3)
self.submit.grid(row=1, column=1)
self.cancel.grid(row=1, column=2)
self.remove_button.grid(row=1, column=0)
def submit(self):
#expose the internal IDs to remove to the exterior methods
self.ids = self.ids_internal
self.top.destroy()
def remove_line(self):
"""Take the active line and remove it"""
line_to_remove = self.current_lines_listbox.get(ANCHOR)
id_to_remove = int(line_to_remove.split(" ")[0])
#remove it from the ID list
self.ids_internal.remove(id_to_remove)
#remove it from the listbox
self.current_lines_listbox = self.current_lines_listbox.delete(ANCHOR)
示例2: CreateSets
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
class CreateSets(Frame):
def __init__(self, parent):
# super(createSets,self).__init__(parent)
Frame.__init__(self, parent)
self.parent = parent
self.grid(row=0, column=0)
self.parentWindow = 0
self.listBox = Listbox(self, selectmode=EXTENDED)
self.listBox.grid(row=1, column=1)
for item in ["one", "two", "three", "four"]:
self.listBox.insert(END, item)
self.buttonDel = Button(self,
text="delite selected class",
command=self.del_selected) # lambda ld=self.listBox:ld.delete(ANCHOR))
self.buttonDel.grid(row=0, column=0)
self.entry = Entry(self, state=NORMAL)
# self.entry.focus_set()
self.entry.insert(0, "default")
self.entry.grid(row=1, column=0)
self.buttonInsert = Button(self, text="add new class",
command=self.add)
self.buttonInsert.grid(row=0, column=1)
self.buttonDone = Button(self, text="done", command=self.done)
self.buttonDone.grid(row=2, column=0)
def done(self):
self.parentWindow.childResultList = self.listBox.get(0, END)
# print(self.listBox.get(0, END))
self.parent.destroy()
def add(self):
text = self.entry.get()
self.listBox.insert(END, text)
def del_selected(self):
lb = self.listBox
items = map(int, lb.curselection())
for item in items:
lb.delete(item)
示例3: Searcher
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
class Searcher(Frame):
""" Keyword Searcher
This is a very simple python program, which is designed for finding specified key-word
in files. Just for fun!
"""
def __init__(self, master=None, cnf={}, **kwargs):
super(Searcher, self).__init__(master, cnf, **kwargs)
self._root_path_var = StringVar()
self._keyword_var = StringVar(self)
self._listbox = None
self._result_queue = None
self.pack(fill=BOTH, expand=YES, padx=5, pady=5)
self.make_widgets()
self._consumer()
# config for main window
self.master.title('Keyword Searcher')
def make_widgets(self):
frm1 = Frame(self)
frm1.pack(side=TOP, fill=X)
Entry(frm1, textvariable=self._root_path_var, font=DEFAULT_FONT).pack(side=LEFT, fill=X, expand=YES)
Button(frm1, text='Add directory', font=DEFAULT_FONT,
command=lambda: self._root_path_var.set(askdirectory(title='Add directory'))).pack(side=RIGHT)
frm2 = Frame(self)
frm2.pack(side=TOP, fill=X)
keyword_ent = Entry(frm2, textvariable=self._keyword_var, font=DEFAULT_FONT)
keyword_ent.pack(side=LEFT, fill=X, expand=YES)
Button(frm2, text='Find', font=DEFAULT_FONT, command=self.find).pack(side=RIGHT)
vs = Scrollbar(self)
hs = Scrollbar(self)
self._listbox = Listbox(self)
vs.pack(side=RIGHT, fill=Y)
vs.config(command=self._listbox.yview)
hs.pack(side=BOTTOM, fill=X)
hs.config(command=self._listbox.xview, orient='horizontal')
self._listbox.config(yscrollcommand=vs.set, xscrollcommand=hs.set,
font=DEFAULT_FONT)
self._listbox.pack(fill=BOTH, expand=YES)
self._listbox.bind('<Double-1>', self._navigate_to)
def find(self):
self._result_queue = queue.Queue()
self._listbox.delete('0', 'end')
Thread(target=self._find, args=(self._root_path_var.get(),
self._keyword_var.get()), daemon=True).start()
def _find(self, path, keyword):
if not os.path.exists(path):
return None
for this_dir, sub_dirs, files in os.walk(path):
for file in files:
file_type = guess_type(file)[0]
if file_type and 'text' in file_type:
fp = os.path.join(this_dir, file)
self._result_queue.put(fp) if keyword in open(fp).read() else None
def _consumer(self):
if self._result_queue:
try:
fp = self._result_queue.get(block=False)
except queue.Empty:
pass
else:
self._listbox.insert('end', fp)
# auto scroll.
self._listbox.yview('end')
self.after(100, self._consumer)
def _navigate_to(self, event):
"""
Only works on Ubuntu platform currently.
Double click to navigate to selected path.
It's a very convenient function.
:return: None
"""
print(event)
# get active item from listbox
path = self._listbox.get('active')
print(path)
# open nautilus with param path, before that, check your platform.
if 'ubuntu' in (os.popen('uname -a').read()).lower():
os.system('/usr/bin/nautilus {}'.format(path))
else:
pass
示例4: Add_Recipe_Modal
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [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()
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [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
示例6: ProblemBrowser
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [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
示例7: LucteriosMainForm
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
class LucteriosMainForm(Tk):
def __init__(self):
Tk.__init__(self)
try:
img = Image("photo", file=join(
dirname(import_module('lucterios.install').__file__), "lucterios.png"))
self.tk.call('wm', 'iconphoto', self._w, img)
except:
pass
self.has_checked = False
self.title(ugettext("Lucterios installer"))
self.minsize(475, 260)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.running_instance = {}
self.resizable(True, True)
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.ntbk = ttk.Notebook(self)
self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))
self.create_instance_panel()
self.create_module_panel()
stl = ttk.Style()
stl.theme_use("default")
stl.configure("TProgressbar", thickness=5)
self.progress = ttk.Progressbar(
self, style="TProgressbar", orient='horizontal', mode='indeterminate')
self.progress.grid(row=1, column=0, sticky=(E, W))
self.btnframe = Frame(self, bd=1)
self.btnframe.grid(row=2, column=0, columnspan=1)
Button(self.btnframe, text=ugettext("Refresh"), width=20, command=self.refresh).grid(
row=0, column=0, padx=3, pady=3, sticky=(N, S))
self.btnupgrade = Button(
self.btnframe, text=ugettext("Search upgrade"), width=20, command=self.upgrade)
self.btnupgrade.config(state=DISABLED)
self.btnupgrade.grid(row=0, column=1, padx=3, pady=3, sticky=(N, S))
Button(self.btnframe, text=ugettext("Close"), width=20, command=self.on_closing).grid(
row=0, column=2, padx=3, pady=3, sticky=(N, S))
def on_closing(self):
all_stop = True
instance_names = list(self.running_instance.keys())
for old_item in instance_names:
if (self.running_instance[old_item] is not None) and self.running_instance[old_item].is_running():
all_stop = False
if all_stop or askokcancel(None, ugettext("An instance is always running.\nDo you want to close?")):
self.destroy()
else:
self.refresh()
def destroy(self):
instance_names = list(self.running_instance.keys())
for old_item in instance_names:
if self.running_instance[old_item] is not None:
self.running_instance[old_item].stop()
del self.running_instance[old_item]
Tk.destroy(self)
def create_instance_panel(self):
frm_inst = Frame(self.ntbk)
frm_inst.grid_columnconfigure(0, weight=1)
frm_inst.grid_rowconfigure(0, weight=1)
frm_inst.grid_columnconfigure(1, weight=3)
frm_inst.grid_rowconfigure(1, weight=0)
self.instance_list = Listbox(frm_inst, width=20)
self.instance_list.bind('<<ListboxSelect>>', self.select_instance)
self.instance_list.pack()
self.instance_list.grid(row=0, column=0, sticky=(N, S, W, E))
self.instance_txt = Text(frm_inst, width=75)
self.instance_txt.grid(row=0, column=1, rowspan=2, sticky=(N, S, W, E))
self.instance_txt.config(state=DISABLED)
self.btninstframe = Frame(frm_inst, bd=1)
self.btninstframe.grid(row=1, column=0, columnspan=1)
self.btninstframe.grid_columnconfigure(0, weight=1)
Button(self.btninstframe, text=ugettext("Launch"), width=25, command=self.open_inst).grid(
row=0, column=0, columnspan=2, sticky=(N, S))
Button(self.btninstframe, text=ugettext("Modify"), width=10,
command=self.modify_inst).grid(row=1, column=0, sticky=(N, S))
Button(self.btninstframe, text=ugettext("Delete"), width=10,
command=self.delete_inst).grid(row=1, column=1, sticky=(N, S))
Button(self.btninstframe, text=ugettext("Save"), width=10,
command=self.save_inst).grid(row=2, column=0, sticky=(N, S))
Button(self.btninstframe, text=ugettext("Restore"), width=10,
command=self.restore_inst).grid(row=2, column=1, sticky=(N, S))
Button(self.btninstframe, text=ugettext("Add"), width=25, command=self.add_inst).grid(
row=3, column=0, columnspan=2, sticky=(N, S))
self.ntbk.add(frm_inst, text=ugettext('Instances'))
def create_module_panel(self):
frm_mod = Frame(self.ntbk)
frm_mod.grid_columnconfigure(0, weight=1)
frm_mod.grid_rowconfigure(0, weight=1)
self.module_txt = Text(frm_mod)
#.........这里部分代码省略.........
示例8: LogUI
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
#.........这里部分代码省略.........
relationlable = Label(frame, text="Relation")
relationlable.grid(row=0, column=1, columnspan=1, sticky=E)
self.condrelationvar = StringVar(frame)
relationinput = Combobox(frame, textvariable=self.condrelationvar, values=["and", "or"])
relationinput.grid(row=0, column=2, padx=5, sticky=E)
relationinput.bind('<<ComboboxSelected>>', self._onrelationchange)
self.searchcondlist = Listbox(frame)
self.searchcondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
vsl = Scrollbar(frame, orient=VERTICAL)
vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
hsl = Scrollbar(frame, orient=HORIZONTAL)
hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
self.searchcondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
hsl.config(command=self.searchcondlist.xview)
vsl.config(command=self.searchcondlist.yview)
newbtn = Button(frame, text="New", width=7, command=self._addsearchcondition)
newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
delbtn = Button(frame, text="Delete", width=7, command=self._deletesearchcondition)
delbtn.grid(row=3, column=1, sticky=E)
modbtn = Button(frame, text="Update", width=7, command=self._modifysearchcondition)
modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
def _onrelationchange(self, evt):
selectedmodel = self._getselectedfile()
selectedmodel.relation = self.condrelationvar.get()
def _inflatesearchcondlist(self, filemodel):
self.condrelationvar.set(filemodel.relation)
conds = filemodel.searchconds
self.searchcondlist.delete(0, END)
for cond in conds:
self.searchcondlist.insert(END, cond.tostring())
def _initjoincondpanel(self):
frame = Frame(self)
frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
label = Label(frame, text="Join Condition: ")
label.grid(sticky=N + W)
self.joincondlist = Listbox(frame)
self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
vsl = Scrollbar(frame, orient=VERTICAL)
vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
hsl = Scrollbar(frame, orient=HORIZONTAL)
hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
hsl.config(command=self.joincondlist.xview)
vsl.config(command=self.joincondlist.yview)
示例9: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
#.........这里部分代码省略.........
text="External dependencies",
variable=self.box,
value="External dependencies",
command=self.refresh_results_window,
)
stat = Radiobutton(
radio_frame,
text="Statistics by type",
variable=self.box,
value="Statistics by type",
command=self.refresh_results_window,
)
msgCat = Radiobutton(
radio_frame,
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"""
示例10: AutocompleteEntry
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [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']
示例11: piano_robot_frame
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
def piano_robot_frame(root, dc):
song_list = []
name_list = []
piano_frame = ttk.Frame(root, padding=(3, 3), relief='raised')
# Images
# record_image = tkinter.PhotoImage(master=root, file='record_image.gif')
# stop_image = tkinter.PhotoImage(file='black.square.gif')
# play_image = tkinter.PhotoImage(file='play.gif')
# Widgets for frame
intro_label1 = ttk.Label(piano_frame, text='Welcome to the roomba piano!')
intro_label2 = ttk.Label(piano_frame, text='Enter the duration for the notes')
intro_label3 = ttk.Label(piano_frame, text='to be played (max 255):')
duration_entry = ttk.Entry(piano_frame, width=5)
recording_label1 = ttk.Label(piano_frame, text='Press the record button, then play a song.')
recording_label2 = ttk.Label(piano_frame, text='Press stop when it is finished, give it a name,')
recording_label3 = ttk.Label(piano_frame, text='and then press save to add it to your list. You')
recording_label4 = ttk.Label(piano_frame, text='can play that song at any time by selecting')
recording_label5 = ttk.Label(piano_frame, text='it in the box and then pressing play.')
record_button = ttk.Button(piano_frame, text='Record', width=6)
stop_button = ttk.Button(piano_frame, text='Stop', width=5)
play_button = ttk.Button(piano_frame, text='Play Song')
saved_songs_listbox = Listbox(piano_frame, height=6, width=30, selectmode='SINGLE')
save_label = ttk.Label(piano_frame, text='Give your song a title:')
save_entry = ttk.Entry(piano_frame, width=15)
save_button = ttk.Button(piano_frame, text='Save Song')
# delete_button = ttk.Button(piano_frame, text='Delete Song')
# White keys constructed
white_note_values = [31, 33, 35, 36, 38, 40, 41, 43, 45, 47, 48, 50,
52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69, 71,
72, 74, 76, 77, 79, 81, 83, 84, 86, 88, 89, 91,
93, 95, 96, 98, 100, 101, 103, 105, 107, 108, 110,
112, 113, 115, 117, 119, 120, 122, 124, 125, 127]
letter_notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
white_keys = []
for k in range(len(white_note_values)):
white_keys = white_keys + [ttk.Button(piano_frame, width=2)]
# Sets text for white keys
white_keys[0]['text'] = 'G'
index = 0
for k in range(1, len(white_keys)):
white_keys[k]['text'] = letter_notes[index]
index = index + 1
if index > 6:
index = 0
# White keys' commands
for k in range(len(white_keys)):
set_index(white_keys, k, dc, white_note_values, duration_entry)
# Widget commands
record_button['command'] = lambda: record_song(dc, 'start')
stop_button['command'] = lambda: record_song(dc, None)
save_button['command'] = lambda: add_song_to_list(dc, save_entry.get(), saved_songs_listbox, song_list, name_list)
play_button['command'] = lambda: play_song(dc, saved_songs_listbox.get('active'), song_list, name_list)
# delete_button['command'] = lambda: delete_song(name_list, song_list, saved_songs_listbox)
# Grid the keys
piano_frame.grid()
intro_label1.grid(row=0, columnspan=10, sticky='W')
intro_label2.grid(row=1, columnspan=10, sticky='W')
intro_label3.grid(row=2, columnspan=10, sticky='W')
duration_entry.grid(row=2, column=6, columnspan=2, sticky='E')
recording_label1.grid(row=0, column=12, columnspan=12, sticky='W')
recording_label2.grid(row=1, column=12, columnspan=12, sticky='W')
recording_label3.grid(row=2, column=12, columnspan=12, sticky='W')
recording_label4.grid(row=3, column=12, columnspan=12, sticky='W')
recording_label5.grid(row=4, column=12, columnspan=12, sticky='W')
record_button.grid(row=1, column=28, columnspan=2, sticky='W')
stop_button.grid(row=1, column=30, columnspan=2, sticky='W')
play_button.grid(row=1, column=32, columnspan=5, sticky='W')
saved_songs_listbox.grid(row=0, rowspan=5, column=38, columnspan=10)
save_label.grid(row=0, column=26, columnspan=12, sticky='W')
save_entry.grid(row=0, column=32, columnspan=12, sticky='W')
save_button.grid(row=2, column=28, columnspan=4)
# delete_button.grid(row=2, column=32, columnspan=5, sticky='W')
for k in range(len(white_keys)):
white_keys[k].grid(row=10, column=k, pady=3)
示例12: GetKeysDialog
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [as 别名]
class GetKeysDialog(Toplevel):
# Dialog title for invalid key sequence
keyerror_title = 'Key Sequence Error'
def __init__(self, parent, title, action, current_key_sequences,
*, _htest=False, _utest=False):
"""
parent - parent of this dialog
title - string which is the title of the popup dialog
action - string, the name of the virtual event these keys will be
mapped to
current_key_sequences - list, a list of all key sequence lists
currently mapped to virtual events, for overlap checking
_htest - bool, change box location when running htest
_utest - bool, do not wait when running unittest
"""
Toplevel.__init__(self, parent)
self.withdraw() # Hide while setting geometry.
self.configure(borderwidth=5)
self.resizable(height=False, width=False)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.parent = parent
self.action = action
self.current_key_sequences = current_key_sequences
self.result = ''
self.key_string = StringVar(self)
self.key_string.set('')
# Set self.modifiers, self.modifier_label.
self.set_modifiers_for_platform()
self.modifier_vars = []
for modifier in self.modifiers:
variable = StringVar(self)
variable.set('')
self.modifier_vars.append(variable)
self.advanced = False
self.create_widgets()
self.update_idletasks()
self.geometry(
"+%d+%d" % (
parent.winfo_rootx() +
(parent.winfo_width()/2 - self.winfo_reqwidth()/2),
parent.winfo_rooty() +
((parent.winfo_height()/2 - self.winfo_reqheight()/2)
if not _htest else 150)
) ) # Center dialog over parent (or below htest box).
if not _utest:
self.deiconify() # Geometry set, unhide.
self.wait_window()
def showerror(self, *args, **kwargs):
# Make testing easier. Replace in #30751.
messagebox.showerror(*args, **kwargs)
def create_widgets(self):
self.frame = frame = Frame(self, borderwidth=2, relief='sunken')
frame.pack(side='top', expand=True, fill='both')
frame_buttons = Frame(self)
frame_buttons.pack(side='bottom', fill='x')
self.button_ok = Button(frame_buttons, text='OK',
width=8, command=self.ok)
self.button_ok.grid(row=0, column=0, padx=5, pady=5)
self.button_cancel = Button(frame_buttons, text='Cancel',
width=8, command=self.cancel)
self.button_cancel.grid(row=0, column=1, padx=5, pady=5)
# Basic entry key sequence.
self.frame_keyseq_basic = Frame(frame, name='keyseq_basic')
self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew',
padx=5, pady=5)
basic_title = Label(self.frame_keyseq_basic,
text=f"New keys for '{self.action}' :")
basic_title.pack(anchor='w')
basic_keys = Label(self.frame_keyseq_basic, justify='left',
textvariable=self.key_string, relief='groove',
borderwidth=2)
basic_keys.pack(ipadx=5, ipady=5, fill='x')
# Basic entry controls.
self.frame_controls_basic = Frame(frame)
self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5)
# Basic entry modifiers.
self.modifier_checkbuttons = {}
column = 0
for modifier, variable in zip(self.modifiers, self.modifier_vars):
label = self.modifier_label.get(modifier, modifier)
check = Checkbutton(self.frame_controls_basic,
command=self.build_key_string, text=label,
variable=variable, onvalue=modifier, offvalue='')
check.grid(row=0, column=column, padx=2, sticky='w')
self.modifier_checkbuttons[modifier] = check
column += 1
#.........这里部分代码省略.........
示例13: TextSelect
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import get [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."""
#.........这里部分代码省略.........