Search code examples
pythonsearchtkintertextboxtkinter-entry

How to put a textbox into a python tkinter application?


I've looked at several other questions and none of them seem to help with my solution. I think I'm just not very intelligent sadly.

Basic question I know. I decided to learn python and I'm making a basic app with tkinter to learn.

Basically it's an app that stores and displays people's driving licence details (name and expiry date). One of the abilities I want it to have is a name lookup. To begin with, I need to figure out how to put a textbox into my window!

I will post the relevant (well, what I think is relevant!) code below:

class search(tk.Frame):


def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Enter a name to display that individual's details", font=LARGE_FONT)
    label.pack(pady=10,padx=10)     

    label1 = tk.Label(console, text="Name:").pack()
    searchbox = tk.Entry(console)
    searchbox.pack()


    button1 = tk.Button(self, text="SEARCH", command=lambda: controller.show_frame(main))#not created yet
    button1.pack()

    button2 = tk.Button(self, text="HOME", command=lambda: controller.show_frame(main))
    button2.pack()

and of course at the top I have

import tkinter as tk

When I try and run this I get "typeobject "search" has no attribute 'tk'". It worked fine - the search window would open when I click the relevant button on the home window. Until I tried to add the Entry box.

What am I doing wrong here? I'm an utter newbie so I'm prepared to face my stupidity

Also apologies if the formatting of this question is awful, I'm a newbie posting here as well. Putting everything into correct "code" format is a real pain


Solution

  • I'm guessing you're running into problems since you didn't specify a layout manager and passed console instead of self:

    import tkinter as tk
    
    class Search(tk.Frame):
        def __init__(self, parent=None, controller=None):
            tk.Frame.__init__(self, parent)
    
            self.pack()  # specify layout manager
    
            label1 = tk.Label(self, text="Enter a name to display that individual's details")
            label1.pack(pady=10, padx=10)
    
            label2 = tk.Label(self, text="Name:")
            label2.pack()
    
            searchbox = tk.Entry(self)
            searchbox.pack()
    
            button1 = tk.Button(self, text="SEARCH", command=lambda: controller.show_frame(main))
            button1.pack()
    
            button2 = tk.Button(self, text="HOME", command=lambda: controller.show_frame(main))
            button2.pack()
    
    # Just cobble up the rest for example purposes:
    
    main = None
    
    class Controller:
        def show_frame(self, frame=None):
            pass
    
    app = Search(controller=Controller())
    app.mainloop()