8

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
IcyFlame
  • 5,059
  • 21
  • 50
  • 74

2 Answers2

11

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

IcyFlame
  • 5,059
  • 21
  • 50
  • 74
  • 1
    why are you declaring `global e`? As `e` was defined outside the function, it's already global, right? – Lucas Jan 04 '20 at 18:02
  • @Hartnäckig [Aah, this.](https://stackoverflow.com/questions/12665994/function-not-changing-global-variable) – Mooncrater Jan 31 '20 at 13:03
-2
from tkinter import *

root = Tk()
root.title("lol")
root.geometry("400x400")

input = Entry(root)
input.pack()

root.mainloop()
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality. Also check the [help center](https://stackoverflow.com/editing-help) for info on how to format code. – Tyler2P Dec 19 '21 at 10:30