Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking input from the user in Tkinter

Tags:

python

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?

Specs Python 2.7 on Linux Mint 14

like image 825
IcyFlame Avatar asked Mar 19 '13 09:03

IcyFlame


People also ask

How do you take inputs from a GUI?

You need to have JTextField placed in your gui. Input should be done on the textboxes. You also need Jbutton. Buttons are needed for interaction between the user and your program.

How do I print and have user input in a text box in Tkinter?

We can use the Tkinter text widget to insert text, display information, and get the output from the text widget. To get the user input in a text widget, we've to use the get() method.


1 Answers

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

like image 114
IcyFlame Avatar answered Oct 12 '22 22:10

IcyFlame