2

I am using Python 3.2 for Windows with Tkinter 8.5. Does anyone knows if it is possible to open text file by selecting an item on a listbox and display the text file contents on a text widget? Here is my code:

def starters_menu():
        self.listBox.delete(0, END)
        starters_menu = open("starters_menu.txt")
        for line in starters_menu:
            line = line.rstrip()
            self.listBox.insert(END, line)
        self.listBox.bind("<ButtonRelease-1>", recipe_title, add="+")
        self.listBox.bind("<ButtonRelease-1>", recipe_ingredients, add="+")
    recipe_menu.add_command(label="Starters, Snacks and Savouries", command=starters_menu)

I need help to write the definition for "recipe_ingredients" so that when the item in the list is selected, a text file linked to the item is opened and its contents displayed in text widget. I need to know how how to link a file to the listbox item and how to call it using the handler shown in the code above.

1 Answer 1

2

Text Files

You can open a text file and dump it's contents into a string like so:

textFile = open(filename, 'r')
#open() returns a file object
#'r' opens the file for reading. 'w' would be writing
textString = textFile.read()
#This takes the file object opened with the open() and turns it into a string which
#you can now use textString in a text widget.

More info on text files and Python

Linking listbox with text files

To link listbox items with a text files, I suppose you could have all the things you are putting in the listbox in a dictionary, more info here. Unlike arrays or lists, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. So for instance you could have a filename as the key and whatever you want in the listbox as the value.

I hope I helped a bit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.