Question

I have this problem in Tkinter. I wish to import a file (*.txt) with Open Button and save some values with Save Button. I wish to show a Error message when no file is open.

I am wrong becuse i get always this message:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:/Users/samsung/PycharmProjects/test_FirstDensity/openANDread.py", line 30, in save
    if not self.filename.name:
AttributeError: MainWindow instance has no attribute 'filename' 

This is a very simplify example

from Tkinter import *
import tkMessageBox
import Tkinter, Tkconstants, tkFileDialog

class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("input")
        self.master.minsize(250, 150)
        self.grid(sticky=E+W+N+S)

        top=self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        for i in range(2):self.rowconfigure(i, weight=1)
        self.columnconfigure(1, weight=1)

        self.button0 = Button(self, text="open", command=self.askopenfilename, activeforeground="red")
        self.button0.grid(row=0, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)

        self.button1 = Button(self, text="save", command=self.save, activeforeground="red")
        self.button1.grid(row=1, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)

    def askopenfilename(self):
        self.filename = tkFileDialog.askopenfilename(filetypes=[("Text Files",'.txt')])
        return self.filename.name

    def save(self):
        if not self.filename.name:
            tkMessageBox.showerror("Error", message="None file to save")
            return
Was it helpful?

Solution

It seems like you are calling the save() method before calling the askopenfilename() method. That's why, you get the AttributeError. Make sure the flow of your code reflects this change.

You might also want to include proper error handling in your askopenfilename() method itself to include situations where no file is opened.

You could do something on these lines. First initialize the self.filename = None in your constructor for the MainWindow class. Then you could modify your method as such:

def askopenfilename(self):
        self.filename = tkFileDialog.askopenfilename(filetypes=[("Text Files",'.txt')])
        if not self.filename: return None
        return self.filename.name

However this is just to give you an idea, I have not myself worked with Tkinter much. All in all, it would depend on what exactly you are trying to achieve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top