-1

below is my code for creating a tool that takes a file path, stores the value, and then opens the specific file path selected by the user.

Currently, I'm looking to take the user entry mypathEntry that is stored in the mypathList listbox after clicking the Save button and add a command to it. The command will open that selected file path. My current code returns an error message regarding mypathList.add_command(command=Open) stating that Listbox instance has no attribute 'add_command'.

What is the syntax for adding a command to a listbox item?

from Tkinter import *
import os

root = Tk()

def Save():
    fp = mypathEntry.get()
    scribe = open('filepath.txt', 'w')
    scribe.write(fp)
    mypathEntry.delete(0, 'end')
    mypathList.insert(1, fp)

def Open():
    path = fp

menu = Menu(root)
##root.config(menu=menu)

##subMenu = Menu(menu)
##menu.add_cascade(label="Filepaths", menu=subMenu)
##subMenu.add_command(command=Save)

mypathLabel = Label(root, text="Copy and Paste your filepath here:")
mypathEntry = Entry(root, bg="black", fg="white", relief=SUNKEN)
mypathSaveButton = Button(root, text="Save Path", bg="black", fg="white", command=Save)

mypathList = Listbox(root, bg="black", fg="white")
mypathList.add_command(command=Open)


mypathLabel.pack()
mypathEntry.pack()
mypathSaveButton.pack()
mypathList.pack()



root.mainloop()
mattyb
  • 11
  • 1
  • 8

1 Answers1

2

According to this, http://effbot.org/tkinterbook/listbox.htm The listbox item does not have a command option. So what you need to do instead is to bind an event to it. Here is a complete working example.

from tkinter import *
import os

root = Tk()
class MainGui:
    def __init__(self, master):
        self.mypathLabel = Label(master, text="Copy and Paste your filepath here:")
        self.mypathEntry = Entry(master, bg="black", fg="white", relief=SUNKEN)
        self.mypathSaveButton = Button(master, text="Save Path", bg="black", fg="white", command=self.save_path)
        self.mypathList = Listbox(master, bg="black", fg="white")

        self.mypathLabel.pack()
        self.mypathEntry.pack()
        self.mypathSaveButton.pack()
        self.mypathList.pack()
        self.mypathList.bind("<Double-Button-1>", self.open_path)

    def save_path(self):
        fp = self.mypathEntry.get()
        self.mypathEntry.delete(0, 'end')
        self.mypathList.insert(1, fp)

    def open_path(self, event):
        list_item = self.mypathList.curselection()
        fp = self.mypathList.get(list_item[0])
        print(fp)
        try:
            with open(fp, 'r') as result:
                print(result.read())
        except Exception as e:
            print(e)    

MainGui(root)
root.mainloop()
terratunaz
  • 614
  • 3
  • 9
  • 19