Saturday, 26 November 2016

Python Listbox delete text

In this video you will learn to delete a selected item in a listbox tkinter widget using Python3



# Craig Hammond 2016
from tkinter import 
from tkinter import ttk

class Application(Frame):
    
    def __init__(self, master):
        """ Initialize the Frame """
        ttk.Frame.__init__(self, master)
 
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        # create the button widgets
        self.btnAddSymbol = ttk.Button(self, text = "Add Symbol", command=self.add_symbol).grid(row=0, column=0, sticky=W)    
        self.tbEntry = Entry(self, font=('', 12), textvariable=varEntry).grid(row=0, column=1, sticky=W)
        self.btnDeleteSymbol = ttk.Button(self, text = 'Remove Symbol', command=self.delete_symbol).grid(row=0, column=2, sticky=W)

        # create listbox widget
        self.listbox1 = Listbox(self, font=('', 12))
        #self.listbox1.bind('<ButtonRelease-1>', self.select_item) # Don't use  it won't work
        self.listbox1.bind('<<ListboxSelect>>', self.select_item)
        self.listbox1.insert(1, 'EVIL')
        self.listbox1.insert(2, 'SBUX')
        self.listbox1.insert(3, 'FB')
        self.listbox1.grid(row=1, column=0)
        
    def add_symbol(self):
        to_add = varEntry.get() # gets text from textbox or Entry box
        # change 'end' to 0 to add it to the beginning
        self.listbox1.insert('end', to_add) # adds text to listbox 
        
    def select_item(self, event):
        pass
        
    def delete_symbol(self):
        current_selection = self.listbox1.curselection() # gets the position of the selected item
        # print (current_selection)
        self.listbox1.delete(current_selection) # deletes the selected item

root = Tk()
varEntry = StringVar(root, value="SCTY")
app = Application(root)
root.mainloop()

No comments:

Post a Comment