官术网_书友最值得收藏!

Adding a label to the GUI form

Getting ready

We are extending the first recipe. We will leave the GUI resizable, so don't use the code from the second recipe (or comment the win.resizable line 4 out).

How to do it...

In order to add a Label widget to our GUI, we are importing the ttk module from tkinter. Please note the two import statements.

# imports                  # 1
import tkinter as tk       # 2
from tkinter import ttk    # 3

Add the following code just above win.mainloop() located at the bottom of recipes 1 and 2.

# Adding a Label           # 4
ttk.Label(win, text="A Label").grid(column=0, row=0) # 5

Running the code adds a label to our GUI:

How it works...

In line 3 of the above code, we are importing a separate module from tkinter. The ttk module has some advanced widgets that make our GUI look great. In a sense, ttk is an extension within tkinter.

We still need to import tkinter itself, but we have to specify that we now want to also use ttk from tkinter.

Note

ttk stands for 'themed tk". It improves our GUI look and feel.

Line 5 above adds the label to the GUI, just before we call mainloop (not shown here to preserve space. See recipes 1 or 2).

We are passing our window instance into the ttk.Label constructor and setting the text property. This becomes the text our Label will display.

We are also making use of the grid layout manager, which we'll explore in much more depth in Chapter 2, Layout Management.

Note how our GUI suddenly got much smaller than in previous recipes.

The reason why it became so small is that we added a widget to our form. Without a widget, tkinter uses a default size. Adding a widget causes optimization, which generally means using as little space as necessary to display the widget(s).

If we make the text of the label longer, the GUI will expand automatically. We will cover this automatic form size adjustment in a later recipe in Chapter 2, Layout Management.

There's more...

Try resizing and maximizing this GUI with a label and watch what happens.

主站蜘蛛池模板: 古田县| 南充市| 开江县| 巩留县| 曲周县| 灵丘县| 射阳县| 辽中县| 西丰县| 定结县| 宁远县| 东丰县| 龙陵县| 涿州市| 蓬安县| 五寨县| 靖远县| 庆元县| 司法| 思茅市| 扎兰屯市| 宜丰县| 宜章县| 察隅县| 库伦旗| 茂名市| 股票| 景谷| 临西县| 朝阳区| 平陆县| 梅河口市| 巢湖市| 东阳市| 舒城县| 东辽县| 荥经县| 随州市| 黑水县| 邵阳市| 卢湾区|