Python GUI Tutorial: How To Create A Label In Tkinter
У вашего броузера проблема в совместимости с HTML5
In this Python tutorial, we are going to look at how to create a label in Tkinter. This will be our first tutorial showing you how to add content to the main window of our Tkinter window. We will start the tutorial where we left off in the previous tutorial. If you have not seen this tutorial yet we strongly suggest that you read or watch the video at http://learnpythontutorial.com/change-size-main-window-tkinter/.
What Is A Label?
A label is referred to as a widget in Tkinter. Widgets are commonly used interface objects which you think of them as the building blocks of the Tkinter GUI. Labels represent text or images in the Tkinter interface which provide the user with the ability to only view the content. This means the user has no other interaction with the text and images within a label. You can think of a label as just a display. We can use labels as instructions, labels(mind blown), images, guides and other text that does not require action from the user.
How To Create A Label In Tkinter?
We are going to create a simple label that displays text that states "Hello from a label widget" in our main window.
To start we are going to create Python function and call it main_content. The reason we create another function is because we like to keep our code well organized. Within our new function, we need to create an instance(variable) called hello. hello is now the instance for the Label widget. The first parameter inside the Label widget will be our parent where we want to display our text. Think of parent as our location in which we want our text to be displayed. In our case, we want the text to be displayed in the main window which is represented by root. Our second parameter in this widget is the text we want to display we use text='Hello from a label widget'. You can use whatever you like. If you run your program right now you will notice nothing happens we need to add one more line of code.
Displaying The Label
To display the label we need to provide some sort of geometry instructions to the program for the program to understand where to position the label. In this case, we need to use the pack() method. To call the pack method we simply call our instance hello and then call pack method on our instance. Your code should look like hello.pack(). Basically, now the program has instructions where to place the label and the label will now be displayed when you run your program. We will get more into the pack() method shortly.
Now in our terminal, we run our program by entering the containing folder and running python3 firstwindow.py. Our program should fire up with no errors and display a label that states hello from a label widget. If you have any questions or your label is not working leave a comment below and we will do our best to help you.