Search code examples
pythontkinter

Taking input from the user in Tkinter


Goal:

  1. Give the user a text field.
  2. Print the text that he entered in the field once he presses a button below it into the shell.

How is this possible using Tkinter?


Solution

  • We will take the text from the user using the Entry widget. And then we will define a function that will extract the text from this widget and print it out in the shell.

    def printtext():
        global e
        string = e.get() 
        print string   
        
    from Tkinter import *
    root = Tk()
    
    root.title('Name')
    
    e = Entry(root)
    e.pack()
    e.focus_set()
    
    b = Button(root,text='okay',command=printtext)
    b.pack(side='bottom')
    root.mainloop()
    

    The window instance is first created. And then an Entry widget is packed. After that another button widget is also packed. The focus_set method makes sure that the keyboard focus is on the text field when this is run. When the button is pressed it will go to the function which will extract the text from the Entry widget using the get method.

    You can find more about the Entry widget and its methods here: Entry Widget on TKDocs. (archived version)

    For a meatier example, you can also check this page on TkDocs.