0

I have been trying to open a file read from it, modify it and save that file again. I'm having trouble reading the file through the list box I've created to contain its content. I am not too sure what the problem is here. Here is the code below.

import Tkinter
import Tkinter as tk  # gives tk namespace
from Tkinter import *
from ScrolledText import *
import tkFileDialog
import tkMessageBox

root = Tkinter.Tk(className="To Do List py experiment")
textPad = ScrolledText(root, width=100, height=30)
task_list = tk.Listbox(root, width=50, height=6)


def open_task():
    fin = tkFileDialog.askopenfile(mode='r',title='Select a Task File')
    if fin is not None:
        task_list = fin.readlines()
    for item in task_list:
            task_list.insert(tk.END, item)
    fin.close()


def exit():
    if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
    root.destroy()

def about():
    label = tkMessageBox.showinfo("About", "To do List py experiment")


def new_task():
    task_list.insert(tk.END, input.get())


def delete_item():
    """
    delete a selected line from the listbox
    """
    try:
    # get selected line index
    index = task_list.curselection()[0]
    task_list.delete(index)
    except IndexError:
    pass


def get_list(event):
    """
    function to read the listbox selection
    and put the result in an entry widget
    """
    # get selected line index
    index = task_list.curselection()[0]
    # get the line's text
    seltext = task_list.get(index)
    # delete previous text in input
    input.delete(0, 50)
    # now display the selected text
    input.insert(0, seltext)

def set_list(event):
    """
    insert an edited line from the entry widget
    back into the listbox
    """
    try:
    index = task_list.curselection()[0]
    # delete old listbox line
    task_list.delete(index)
    except IndexError:
    index = tk.END
    # insert edited item back into task_list at index
    task_list.insert(index, input.get())


def save_tasks():
    """
    save the current listbox contents to a file
    """
    # get a list of listbox lines
    temp_list = list(task_list.get(0, tk.END))
    # add a trailing newline char to each line
    temp_list = [task + '\n' for task in temp_list]
    # give the file a different name

    if temp_list is not None:
    fout = tkFileDialog.asksaveasfile(mode='w')
    fout.writelines(temp_list)
    fout.close()

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

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open Task File", command=open_task)
filemenu.add_command(label="Save", command=save_tasks)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=exit)


helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About ", command=about)

# create the listbox (note that size is in characters)
#task_list = tk.Listbox(root, width=50, height=6)
task_list.grid(row=0, column=0)

# create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=task_list.yview, orient=tk.VERTICAL)
yscroll.grid(row=0, column=1, sticky=tk.N+tk.S)
task_list.configure(yscrollcommand=yscroll.set)

#task_list.bind("<<ListboxSelect>>", printer)

# use entry widget to display/edit selection
input = tk.Entry(root, width=50)
input.insert(0, 'Write Your Task here')
input.grid(row=1, column=0)
# pressing the enter key will update edited line
input.bind('<Return>', set_list)

#This button is used to add tasks
button_add_task = tk.Button(root, text='Add entry text to listbox', command=new_task)
button_add_task.grid(row=2, column=0, sticky=tk.E)

#This Button is used to call the delete function
button_delete = tk.Button(root, text='Delete selected Task     ', command=delete_item)
button_delete.grid(row=3, column=0, sticky=tk.E)

# left mouse click on a list item to display selection
task_list.bind('<ButtonRelease-1>', get_list)

root.mainloop()

tata

7
  • Also, I find Tkinter file dialog very ugly. If it's possible, is there a way to use the native file browser of say Linux or windows to browse for files if i decide to try it on windows? Commented Mar 23, 2015 at 6:21
  • Your indentation is wrong. can you fix it. Otherwise its difficult to replicate your problem. Also what errors are you getting? Commented Mar 23, 2015 at 6:43
  • My indentation is correct in the IDE that I'm using, the program runs well and does everything except opening and reading a file. Error is Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__ return self.func(*args) File "/home/user/PycharmProjects/Prototype/PrototypeGUI.py", line 18, in open_task task_list.insert(tk.END, item) TypeError: an integer is required Commented Mar 23, 2015 at 6:51
  • basically, i'm only having trouble with the open_task(): function Commented Mar 23, 2015 at 6:56
  • 1
    If you try this on windows you will get the native windows dialog. Commented Mar 23, 2015 at 13:27

1 Answer 1

3

I think I see the problem. This is what I think is happening:

You have a global variable:

task_list = tk.Listbox(root, width=50, height=6)

But in your open_task function you are using local task_list variable:

def open_task():
    fin = tkFileDialog.askopenfile(mode='r',title='Select a Task File')
    if fin is not None:
        task_list = fin.readlines()    #<-- task_list is no longer tk.Listbox. Its local variable.
    for item in task_list:
        task_list.insert(tk.END, item) #<-- so this does not make sense any more.
    fin.close()
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks for the tip, I fixed it like this: def open_task(): fin = tkFileDialog.askopenfile(mode='rb',title='Select a Task File') if fin is not None: task_listread = fin.readlines() for item in task_listread: task_list.insert(tk.END, item) fin.close()

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.