How to Display an Entry in a Label – Tkinter Python 3

Python 3, Tkinter 8.6. GUI examples in Windows 10

Probably one of the most common things to do when using a Graphical User Interface (GUI) is to display something from an entry from the user.

Below is a simple example that allows the user to input text in a Tkinter Entry field and when they click “Enter” or use the <Return> or <Enter> button it will be displayed in a Tkinter Label.

The end result will look a little like this:

Display Entry in a Label in Tkinter with Python 3

The Code

The Breakdown

Getting Tkinter Ready

Line 4 to 6 and 30 to 32 sets up the window in a look. Geometry on line 30 is called to position it a little closer to center.

Creating the Widgets

myEntry

The first widget set (line 15-19) creates the Entry bar with the variable myEntry. Entry creates a single line widget that the user can add text to.

On the second line of myEntry the focus is set so that when the program is first run the user can just start typing in the entry field.

This variable is then bound to the <Return> key – also known as the <Enter> key. When <Enter> is pressed, it will run the returnEntry function.

Note: When using key binding, the action will return a value with a heap of data in it like follows: 

<KeyPress event state=Mod1 keysym=Return keycode=13 char='\r' x=69 y=24>

We won’t be using this, but it does mean we will need to create an argument in our returnEntry function or we will get an error.

Finally, we pack the label to display it. We’ll be stacking each widget on top of each other, so a simple pack is fine here.

enterEntry

From line 22-23 we create a Button that, when pressed, will also run the returnEntry function.

enterEntry is then packed to fill the full width of the window.

resultLabel

Here in line 25-26 we create an empty label in preparation for when the returnEntry function is called.

Returning the Entry

def returnEntry

Line 8 creates the returnEntry function.

We have an argument set to None because using the <return>  key binding will give us an argument.

Line 10 results calls the myEntry Entry widget and gets the text and stores it as a string.

Line 11 then updates the resultLabel by using config and enters the results variable.

Finally, line 12 clears the text in the Entry.

Leave a Reply