本文整理汇总了Python中tkinter.Listbox.delete方法的典型用法代码示例。如果您正苦于以下问题:Python Listbox.delete方法的具体用法?Python Listbox.delete怎么用?Python Listbox.delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Listbox
的用法示例。
在下文中一共展示了Listbox.delete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
class SpeciesListDialog:
def __init__(self, parent):
self.parent = parent
self.gui = Toplevel(parent.guiRoot)
self.gui.grab_set()
self.gui.focus()
self.gui.columnconfigure(0, weight=1)
self.gui.rowconfigure(1, weight=1)
Label(self.gui, text="Registered Species:").grid(row=0, column=0, pady=5, padx=5, sticky="w")
self.listRegisteredSpecies = Listbox(self.gui, width=70)
self.buttonAdd = Button(self.gui, text=" + ")
self.buttonDel = Button(self.gui, text=" - ")
self.listRegisteredSpecies.grid(row=1, column=0, columnspan=3, sticky="nswe", pady=5, padx=5)
self.buttonAdd.grid(row=2, column=1, pady=5, padx=5)
self.buttonDel.grid(row=2, column=2, pady=5, padx=5)
# Set (minimum + max) Window size
self.gui.update()
self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
# self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())
self.actionUpdate(None)
self.gui.bind("<<Update>>", self.actionUpdate)
self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)
self.buttonDel.bind("<ButtonRelease>", self.actionDel)
self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)
self.gui.mainloop()
def actionClose(self):
self.parent.guiRoot.event_generate("<<Update>>", when="tail")
self.gui.destroy()
def actionUpdate(self, event):
self.listRegisteredSpecies.delete(0, "end")
for (taxid, name) in self.parent.optimizer.speciesList:
self.listRegisteredSpecies.insert("end", taxid + ": " + name)
def actionDel(self, event):
try:
selection = self.listRegisteredSpecies.selection_get()
selectionSplit = selection.split(": ")
self.parent.optimizer.speciesList.remove((selectionSplit[0], selectionSplit[1]))
self.gui.event_generate("<<Update>>")
except tkinter.TclError:
# no selection
pass
def actionAdd(self, Event):
SpeciesSearchDialog(self.parent, self)
示例2: LabeledListBox
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [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)
示例3: ShapesMenu
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [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)
示例4: DrtGlueDemo
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
listscroll.pack(side="left", fill="y")
# If they select a example, apply it.
self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select)
def _init_readingListbox(self, parent):
self._readingFrame = listframe = Frame(parent)
self._readingFrame.pack(fill="both", side="left", padx=2)
self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings")
self._readingList_label.pack()
self._readingList = Listbox(
self._readingFrame,
selectmode="single",
relief="groove",
background="white",
foreground="#909090",
font=self._font,
selectforeground="#004040",
selectbackground="#c0f0c0",
)
self._readingList.pack(side="right", fill="both", expand=1)
# Add a scrollbar if there are more than 25 examples.
listscroll = Scrollbar(self._readingFrame, orient="vertical")
self._readingList.config(yscrollcommand=listscroll.set)
listscroll.config(command=self._readingList.yview)
listscroll.pack(side="right", fill="y")
self._populate_readingListbox()
def _populate_readingListbox(self):
# Populate the listbox with integers
self._readingList.delete(0, "end")
for i in range(len(self._readings)):
self._readingList.insert("end", (" %s" % (i + 1)))
self._readingList.config(height=min(len(self._readings), 25), width=5)
# If they select a example, apply it.
self._readingList.bind("<<ListboxSelect>>", self._readingList_select)
def _init_bindings(self):
# Key bindings are a good thing.
self._top.bind("<Control-q>", self.destroy)
self._top.bind("<Control-x>", self.destroy)
self._top.bind("<Escape>", self.destroy)
self._top.bind("n", self.next)
self._top.bind("<space>", self.next)
self._top.bind("p", self.prev)
self._top.bind("<BackSpace>", self.prev)
def _init_buttons(self, parent):
# Set up the frames.
self._buttonframe = buttonframe = Frame(parent)
buttonframe.pack(fill="none", side="bottom", padx=3, pady=2)
Button(buttonframe, text="Prev", background="#90c0d0", foreground="black", command=self.prev).pack(side="left")
Button(buttonframe, text="Next", background="#90c0d0", foreground="black", command=self.next).pack(side="left")
def _configure(self, event):
self._autostep = 0
(x1, y1, x2, y2) = self._cframe.scrollregion()
y2 = event.height - 6
self._canvas["scrollregion"] = "%d %d %d %d" % (x1, y1, x2, y2)
self._redraw()
def _init_canvas(self, parent):
示例5: ChatGUI
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
class ChatGUI(Frame):
def __init__(self, parent, conn, title):
#Frame.__init__(self, parent, background="grey")
self.parent = parent
self.conn = conn
self.title = title
self.centerWindow()
self.initUI()
def initUI(self):
self.lineCounter = 0
# create a custom font
self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
self.customFontMessage = font.Font(family="Calibri")
self.parent.title(self.title)
frame = Frame(self.parent)
frame.pack(fill=BOTH, expand=1, side=LEFT)
self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
self.box.insert(END, 'Welcome to Python Chat!')
self.box.config(state=DISABLED)
self.box.pack(expand="yes", fill=BOTH, side=TOP)
self.textarea = Text(frame, width=30, height=5)
#self.textarea.insert(END, "")
self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
self.textarea.pack(expand="yes", fill=BOTH, side=TOP)
okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile)
okButton.pack(expand="no", fill=BOTH, side=TOP)
self.usersFrame = Frame(self.parent)
self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
self.userListbox = Listbox(self.usersFrame, width=3)
self.userListbox.bind("<Double-Button-1>", self.privateChat)
self.userListbox.pack(fill=BOTH, expand=1)
self.updateUsersFrame()
def centerWindow(self):
w = 600
h = 475
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def gettext(self, e): #e sta per event, questo e' un listener
text = self.textarea.get("1.0", END + " - 2c") # 1.0: row:columa - END-2c rimuove l'ultimo carattere, una newline \r\n
self.textarea.delete("0.0", END) #NON VA: il problema e' che viene inviato il carattere di newline ma non incluso nell'area a causa della bind mi sa. Devo escluderlo io
self.sendToServer(text)
def printConversation(self, message):
self.box.config(state=NORMAL)
self.box.insert(END,"\n" + message)
self.lineCounter = self.lineCounter + 2
#m = re.match("\[.*\] From .*\n", self.box.get("0.0", END))
m = re.search("\[.*\].*:", message, re.MULTILINE)
if m is not None:
#print("MATCH")
#print(m.group(0))
#print(str(m.start(0)) + "_" + str(m.end(0)))
#print("COUNTER")
#print(str(self.lineCounter) + "." + str(m.start(0)+1) + "___" + str(self.lineCounter) + "." + str(m.end(0)))
self.box.tag_add("header", str(self.lineCounter) + "." + str(m.start(0)), str(self.lineCounter) + "." + str(m.end(0)))
self.box.tag_config("header", font=self.customFontHeader, foreground = "blue")
self.box.config(state=DISABLED)
#self.box.yview_scroll(10000,"units")
self.box.see(END)
def sendToServer(self, messageToSend):
self.conn.send(messageToSend.encode(encoding='utf_8', errors='strict'))
def sendFile(self):
#aprire una dialog di quelle predefinite (Sfoglia...)
#capire come fare la send di un file sul socket...
pass
def updateUsersFrame(self):
global connectedClients
#.........这里部分代码省略.........
示例6: RecursiveDescentApp
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label='About', underline=0,
command=self.about)
helpmenu.add_command(label='Instructions', underline=0,
command=self.help, accelerator='F1')
menubar.add_cascade(label='Help', underline=0, menu=helpmenu)
parent.config(menu=menubar)
#########################################
## Helper
#########################################
def _get(self, widget, treeloc):
for i in treeloc: widget = widget.subtrees()[i]
if isinstance(widget, TreeSegmentWidget):
widget = widget.label()
return widget
#########################################
## Main draw procedure
#########################################
def _redraw(self):
canvas = self._canvas
# Delete the old tree, widgets, etc.
if self._tree is not None:
self._cframe.destroy_widget(self._tree)
for twidget in self._textwidgets:
self._cframe.destroy_widget(twidget)
if self._textline is not None:
self._canvas.delete(self._textline)
# Draw the tree.
helv = ('helvetica', -self._size.get())
bold = ('helvetica', -self._size.get(), 'bold')
attribs = {'tree_color': '#000000', 'tree_width': 2,
'node_font': bold, 'leaf_font': helv,}
tree = self._parser.tree()
self._tree = tree_to_treesegment(canvas, tree, **attribs)
self._cframe.add_widget(self._tree, 30, 5)
# Draw the text.
helv = ('helvetica', -self._size.get())
bottom = y = self._cframe.scrollregion()[3]
self._textwidgets = [TextWidget(canvas, word, font=self._font)
for word in self._sent]
for twidget in self._textwidgets:
self._cframe.add_widget(twidget, 0, 0)
twidget.move(0, bottom-twidget.bbox()[3]-5)
y = min(y, twidget.bbox()[1])
# Draw a line over the text, to separate it from the tree.
self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')
# Highlight appropriate nodes.
self._highlight_nodes()
self._highlight_prodlist()
# Make sure the text lines up.
self._position_text()
def _redraw_quick(self):
示例7: __init__
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
self._canvas.notify_layer_change()
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"
示例8: Add_Recipe_Modal
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [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()
#.........这里部分代码省略.........
示例9: Example
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
def onTest(self, val):
return "break"
# seleccionar un elementos de una listbox
def onSelect(self, val):
try:
if self.ant != None:
self.listbox.itemconfig(self.ant, background="#FFFFFF")
self.listbox2.itemconfig(self.ant, background="#FFFFFF")
self.listbox3.itemconfig(self.ant, background="#FFFFFF")
self.listbox4.itemconfig(self.ant, background="#FFFFFF")
self.listbox5.itemconfig(self.ant, background="#FFFFFF")
self.listbox.itemconfig(val.widget.curselection(), background="#C0C0C0")
self.listbox2.itemconfig(val.widget.curselection(), background="#C0C0C0")
self.listbox3.itemconfig(val.widget.curselection(), background="#C0C0C0")
self.listbox4.itemconfig(val.widget.curselection(), background="#C0C0C0")
self.listbox5.itemconfig(val.widget.curselection(), background="#C0C0C0")
self.ant = val.widget.curselection()
except:
None
# print('No hay valores')
# dependiendo de que nombre se elija en el menu cargamos en lastLine la linea de ese nombre del diccionario
def onSelectPlayer(self, val):
try:
self.name = val.widget.get(val.widget.curselection())
self.lastLine = optionsDictionary[self.name]
# print(self.name, ' ', self.lastLine)
except:
None
# print('No hay valores')
# recorremos el fichero log al clickar sobre el boton 'Refresh!'
def onRefresh(self):
if self.name != "":
yes = False
count = 0
dictionary = {}
dictionaryAuxiliar = {}
stringLog = "../eqlog_" + str(self.name) + "_project1999.txt"
with open(stringLog, "r") as log:
for i in range(int(self.lastLine)):
next(log)
count = count + 1
for line in log:
match = re.match("\[.*\] \[(.*) (.*)\] (.*) \((.*)\) <.*> ZONE: (.*)", line)
matchRole = re.match("\[.*\] \[(.*)\] (.*) <.*>", line)
matchToken = re.match("\[.*\] You say, 't0000'", line)
matchTokenI = re.match("\[.*\] You say, 't0001'", line)
if matchTokenI != None:
yes = True
elif match != None and yes:
dictionaryAuxiliar[match.group(3)] = (
match.group(1),
match.group(2),
match.group(4),
match.group(5),
)
elif matchRole != None and yes:
dictionaryAuxiliar[matchRole.group(2)] = [(matchRole.group(1))]
elif matchToken != None and yes:
dictionary = dictionaryAuxiliar.copy()
dictionaryAuxiliar.clear()
yes = False
count = count + 1
# bucle para sacar datos, primero eliminamos todo lo que haya
self.listbox.delete(0, self.listbox.size())
self.listbox2.delete(0, self.listbox2.size())
self.listbox3.delete(0, self.listbox3.size())
self.listbox4.delete(0, self.listbox4.size())
self.listbox5.delete(0, self.listbox5.size())
for member in dictionary:
self.listbox.insert(END, member)
self.listbox2.insert(END, dictionary[member][0])
try:
self.listbox3.insert(END, dictionary[member][1])
self.listbox4.insert(END, dictionary[member][2])
self.listbox5.insert(END, dictionary[member][3])
except IndexError as error:
self.listbox3.insert(END, "-")
self.listbox5.insert(END, "-")
self.listbox4.insert(END, "-")
# print(dictionary)
# print('Longitud', len(dictionary))
# guardamos la linea ultima leida en el diccionario
# self.lastLine = count
# optionsDictionary[self.name] = count
# print('Despues:', optionsDictionary)
# guardamos el diccionario en el archivo options
options = open("options.txt", "w")
for player in optionsDictionary:
options.write(str(player) + ":" + str(optionsDictionary[player]))
options.close()
示例10: LucteriosMainForm
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [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)
#.........这里部分代码省略.........
示例11: TextSelect
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
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."""
# first add the character to the entry.
currentText = self.entry.get()
print(event.keysym)
if event.keysym == 'BackSpace':
# Handle backspace specially.
if currentText:
currentText = currentText[:-1]
self.entry.delete(0, 'end')
self.entry.insert(0, currentText)
else:
return 'break'
else:
# Assume normal character. Insert it.
self.entry.insert('insert', event.char)
currentText += event.char
self.list.delete(0, 'end')
pattern = currentText.upper()
for item in self.items:
if pattern in item.upper():
self.list.insert('end', item)
return 'break'
示例12: reactToClick
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick)
self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete)
self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton)
self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence)
self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence)
# TEST
# self.listRestriction.insert("end", "EcoRI")
# self.listRestriction.insert("end", "BamHI")
#
# dummy event to manually trigger update
self.guiRoot.bind("<<Update>>", self.actionUpdate)
self.actionUpdate(None)
self.guiRoot.mainloop()
def actionRestrictionEnzymeDelete(self, event):
try:
selectedEnzyme = self.listRestriction.selection_get()
self.optimizer.restrictionEnzymeList.remove(selectedEnzyme)
self.guiRoot.event_generate("<<Update>>")
except tkinter.TclError:
# no selection
pass
def actionUpdate(self, event):
# print("update called")
# clear list of restriction enzymes
self.listRestriction.delete(0, "end")
for r in self.optimizer.restrictionEnzymeList:
self.listRestriction.insert("end", r)
self.comboSourceSpecies.delete(0, "end")
self.comboTargetSpecies.delete(0, "end")
speciesValues = list()
for (taxid, name) in self.optimizer.speciesList:
speciesValues.append(taxid + ": " + name)
self.comboSourceSpecies["values"] = speciesValues
self.comboTargetSpecies["values"] = speciesValues
if self.comboSourceSpecies.get() not in speciesValues:
self.comboSourceSpecies.set("")
if self.comboTargetSpecies.get() not in speciesValues:
self.comboTargetSpecies.set("")
self.textSourceSeq.edit_modified(True)
self.textResultSequence.edit_modified(True)
self.optimizer.saveConfig("config.ini")
def actionEditSpeciesButton(self, event):
speciesListDialog = SpeciesListDialog(self)
def actionOptimizerSettingsChanged(self, event=None):
# print("Something happened")
strategy = self.comboOptimizationStrategy.get()
sourceString = self.comboSourceSpecies.get()
targetString = self.comboTargetSpecies.get()
示例13: Application
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
#.........这里部分代码省略.........
:param str_points: "x,y,z,w,a,b" string
that each odd nu is x and each even is y
:return: list of coordinates as tuple in format (x,y,x,y,x,y)
"""
nums = str_points.split(',')
return tuple(nums)
def open_help_dialog(self):
"""
This function creates new "help" dialog
:return:
"""
try:
self.help_frame.destroy()
except:
pass
infromative_txt = self.get_informative_text()
self.help_frame = Tk()
self.help_frame.title(HELP_TITLE)
infromative_text = Label(self.help_frame, text=infromative_txt)
infromative_text.pack()
self.help_frame.mainloop()
def get_informative_text(self):
f = open(INFO_DIR, READ_PREM)
reader = f.read()
f.close()
return reader
def open_debug_dialog(self):
"""
this function create new "debug" dialog
:return:
"""
self.debug_frame = Tk()
self.debug_frame.title(DEBUG_TITLE)
self.debug_messages = Text(self.debug_frame)
self.debug_messages.insert(END, "Messages")
self.debug_messages.pack()
self.debug_frame.mainloop()
def debug_event(self, event):
"""
This function check if the debug option is enabled
if it is it will record the event in the debug messages dialog
:param event: string repr event to debug..
"""
if self.debug:
self.debug_messages.insert(END, "\nEVENT: " + str(event))
def on_close(self):
"""
Handles closing the programe
:return:
"""
self.__network.leave_msg()
self.__master_splinter.destroy()
try:
self.debug_frame.destroy()
self.help_frame.destroy()
except:
pass
def change_users_list(self, msg_type, user):
"""
Handle "change user" event (Leave\Join)
:param msg_type: CONSTANT, JOIN\LEAVE
:param user: list of users..
"""
users = user[ONE_USER]
self.debug_event(user + " has " + msg_type)
if msg_type is LEAVE_EVT:
self.remove_user_from_list(users)
elif msg_type is JOIN_EVT:
self.add_user_to_list(users)
def add_user_to_list(self, user):
"""
Add specific user the list_box.. of users list
:param user: string repr username
"""
if user not in self.__users_list:
self.__users_list.append(user)
self.lb_users.insert(END, user)
else:
self.debug_event(user + " already exists")
def remove_user_from_list(self, user):
"""
This function tries to delete specific username
from the list
:param user: string repr username
:return:
"""
try:
i = self.__users_list.index(user)
self.lb_users.delete(i)
self.__users_list.pop(i)
except:
self.debug_event(user + " is not in our list..")
示例14: ChatGUI
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
class ChatGUI(Frame):
def __init__(self, parent, conn):
#Frame.__init__(self, parent, background="grey")
self.parent = parent
self.conn = conn
self.centerWindow()
self.initUI()
def initUI(self):
self.lineCounter = 0
# create a custom font
self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
self.customFontMessage = font.Font(family="Calibri")
self.parent.title("Python Chat")
frame = Frame(self.parent)
frame.pack(fill=BOTH, expand=1, side=LEFT)
self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
self.box.insert(END, 'Welcome to Python Chat!')
self.box.config(state=DISABLED)
self.box.pack(expand="yes", fill=BOTH, side=TOP)
self.textarea = Text(frame, width=30, height=5)
#self.textarea.insert(END, "")
self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
self.textarea.pack(expand="yes", fill=BOTH, side=TOP)
okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile)
okButton.pack(expand="no", fill=BOTH, side=TOP)
self.usersFrame = Frame(self.parent)
self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
self.userListbox = Listbox(self.usersFrame, width=3)
self.userListbox.pack(fill=BOTH, expand=1)
self.updateUsersFrame()
def centerWindow(self):
w = 600
h = 475
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def gettext(self, e): #e sta per event, questo e' un listener
text = self.textarea.get("1.0", END) # 1.0: row:columa - END-2c rimuove l'ultimo carattere, una newline \r\n
if "\n" in text:
text = text.replace("\n", "")
self.textarea.delete("0.0", END) #NON VA: il problema e' che viene inviato il carattere di newline ma non incluso nell'area a causa della bind mi sa. Devo escluderlo io
self.sendToServer(text)
def printConversation(self, message):
self.box.config(state=NORMAL)
self.box.insert(END,"\n" + message)
self.lineCounter = self.lineCounter + 2
#m = re.match("\[.*\] From .*\n", self.box.get("0.0", END))
m = re.search("\[.*\].*:", message, re.MULTILINE)
if m is not None:
#print("MATCH")
#print(m.group(0))
#print(str(m.start(0)) + "_" + str(m.end(0)))
#print("COUNTER")
#print(str(self.lineCounter) + "." + str(m.start(0)+1) + "___" + str(self.lineCounter) + "." + str(m.end(0)))
self.box.tag_add("header", str(self.lineCounter) + "." + str(m.start(0)), str(self.lineCounter) + "." + str(m.end(0)))
self.box.tag_config("header", font=self.customFontHeader, foreground = "blue")
self.box.config(state=DISABLED)
#self.box.yview_scroll(10000,"units")
self.box.see(END)
def sendToServer(self, messageToSend):
self.conn.send(messageToSend.encode(encoding='utf_8', errors='strict'))
def sendFile(self):
#aprire una dialog di quelle predefinite (Sfoglia...)
#capire come fare la send di un file sul socket...
pass
def updateUsersFrame(self):
global connectedClients
#.........这里部分代码省略.........
示例15: LogUI
# 需要导入模块: from tkinter import Listbox [as 别名]
# 或者: from tkinter.Listbox import delete [as 别名]
class LogUI(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.filemodels = []
filemodel1 = FileModel("C:/Users/chen_xi/test1.csv", searchconds=[], relation="and", joincondtuples=[])
filemodel2 = FileModel("C:/Users/chen_xi/test2.csv", searchconds=[], relation="and", joincondtuples=[])
self.filemodels = [filemodel1, filemodel2]
self._initUI()
self.selectedfileindex = -1
def _initUI(self):
self.parent.title("Log Processor")
self.pack()
self._initfilepanel()
self._initsearchcondpanel()
self._initjoincondpanel()
self._initconsole()
self._inflatefilelist()
def _initfilepanel(self):
frame = Frame(self)
frame.grid(row=0, column=0, sticky=E + W + S + N)
label = Label(frame, text="File List: ")
label.grid(sticky=N + W)
self.filelist = Listbox(frame, width=40)
self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
vsl = Scrollbar(frame, orient=VERTICAL)
vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
hsl = Scrollbar(frame, orient=HORIZONTAL)
hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
hsl.config(command=self.filelist.xview)
vsl.config(command=self.filelist.yview)
upbtn = Button(frame, text="Up", width=7, command=self._upfile)
upbtn.grid(row=1, column=4, padx=5, pady=5)
downbtn = Button(frame, text="Down", width=7, command=self._downfile)
downbtn.grid(row=2, column=4, padx=5, pady=5)
newbtn = Button(frame, text="New", width=7, command=self._addfile)
newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
def _inflatefilelist(self):
self.filelist.delete(0, END)
for filemodel in self.filemodels:
self.filelist.insert(END, filemodel.filename)
def _initsearchcondpanel(self):
frame = Frame(self)
frame.grid(row=0, column=1, sticky=E + W + S + N, padx=5)
label = Label(frame, text="Search Condition: ")
label.grid(row=0, column=0, columnspan=1, sticky=W)
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)
#.........这里部分代码省略.........