Search code examples
pythontkinterxlsxwritertkinter-entry

Tkinter Entry Field Capture AttributeError:


I want to capture the data in the entry field from the second window defined under output. When I click submit get the following message: AttributeError: 'NoneType object has no attribute 'get'.

I feel like this should be an easy fix and do not understand why can't I capture the data from the entry field?

from tkinter import *
import xlsxwriter

class MyFirstGUI:
    def __init__ (self, master):
        master.title("Main")
        master.geometry("400x400+230+160")

        button1 = Button(master, text="1", command= self.output).grid(row=0, column=0)


    def output(self):

        cw1= Toplevel(root)
        cw1.title("cw1")
        cw1.geometry("400x300+160+160")

        self.b2 = Button(cw1, text="Submit",command = self.write_to_xlsx).grid(row=0, column=2) 
        self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)

        self.e2 = Entry(cw1).grid(row=0, column=1)


    def write_to_xlsx(self):

        workbook = xlsxwriter.Workbook('tkintertest19.xlsx')
        worksheet = workbook.add_worksheet()
        worksheet.write_string('C1', self.e2.get())
        workbook.close() 


root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

Solution

  • What you need to do is split the line

    self.l2 = Label(cw1, text="New Specimen").grid(row=0, column=0)
    

    into

    self.l2 = Label(cw1, text = "New Specimen")
    self.l2.grid(row=0, column=0)
    

    Non-intuitive as this may seem, the grid/pack/place functions return None, so the whole shebang (Label().grid()) returns None. The solution is simply to split it up so that you get the right thing when you use .get().