Search code examples
pythontkintertkinter-entry

inputting data to Entry widget from button


Hi i am trying to create a simple touchscreen interface that allows users to enter a 4 digit code into the entry widget and then save it to a string. I am unsure of how to do the following: When button pressed input that value into the Entry widget here is my code so far, but i get the following error:

AttributeError: 'NoneType' object has no attribute 'insert'

   def lockscreen():
    locks = Toplevel(width=500,height=500)
    locks.title('Lock Screen')
    L1 = Label(locks,text="Enter 4 Digit Lock Code").grid(row=1,column=1,columnspan=3)
    e1=Entry(locks, bd=5).grid(row=2,column=1,columnspan=3)


    Button(locks, width=3, height=3, text='1', command =lambda:screen_text("1")).grid(row=3,column=1)          
    Button(locks, width=3, height=3, text='2').grid(row=3,column=2)
    Button(locks, width=3, height=3, text='3').grid(row=3,column=3)
    Button(locks, width=3, height=3, text='4').grid(row=4,column=1)
    Button(locks, width=3, height=3, text='5').grid(row=4,column=2)
    Button(locks, width=3, height=3, text='6').grid(row=4,column=3)
    Button(locks, width=3, height=3, text='7').grid(row=5,column=1)
    Button(locks, width=3, height=3, text='8').grid(row=5,column=2)
    Button(locks, width=3, height=3, text='9').grid(row=5,column=3)
    Button(locks, width=3, height=3, text='Close').grid(row=6,column=1)
    Button(locks, width=3, height=3, text='0').grid(row=6,column=2)
    Button(locks, width=3, height=3, text='Enter').grid(row=6,column=3)

    def screen_text(text):
        e1.insert(0,text)
        return



master.mainloop()

Solution

  • The problem is this line:

    e1=Entry(locks, bd=5).grid(row=2,column=1,columnspan=3)
    

    By chaining the Entry() constructor and the grid() call together, you are actually storing the result of the grid() call in e1, not the Entry field. To fix:

    e1=Entry(locks, bd=5)
    e1.grid(row=2,column=1,columnspan=3)
    

    Notes:

    • You have the same issue with the L1 variable
    • You may also want to add commands to your other buttons too

    With solving the new issue from the comments your code becomes something like:

    def lockscreen():
        locks = Toplevel(width=500,height=500)
        locks.title('Lock Screen')
        L1 = Label(locks,text="Enter 4 Digit Lock Code")
        L1.grid(row=1,column=1,columnspan=3)
        e1=Entry(locks, bd=5)
        e1.grid(row=2,column=1,columnspan=3)
    
        def screen_text(text):
            e1.insert(0,text)
    
        Button(locks, width=3, height=3, text='1', 
               command=lambda:screen_text("1")).grid(row=3,column=1)