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

Arranging several labels within a label frame widget

The LabelFrame widget allows us to design our GUI in an organized fashion. We are still using the grid layout manager as our main layout design tool, yet by using LabelFrame widgets we get much more control over our GUI design.

Getting ready

We are starting to add more and more widgets to our GUI, and we will make the GUI fully functional in the coming recipes. Here, we are starting to use the LabelFrame widget. We will reuse the GUI from the last recipe of the previous chapter.

How to do it...

Add the following code just above the main event loop towards the bottom of the Python module:

# Create a container to hold labels
labelsFrame = ttk.LabelFrame(win, text=' Labels in a Frame ') # 1
labelsFrame.grid(column=0, row=7)

# Place labels into the container element # 2
ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0)
ttk.Label(labelsFrame, text="Label2").grid(column=1, row=0)
ttk.Label(labelsFrame, text="Label3").grid(column=2, row=0)

# Place cursor into name Entry
nameEntered.focus()

Note

We can easily align the labels vertically by changing our code, as shown next. Note that the only change we had to make was in the column and row numberings.

# Place labels into the container element – vertically # 3
ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0)
ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1)
ttk.Label(labelsFrame, text="Label3").grid(column=0, row=2)

How it works...

Comment # 1: Here, we will create our first ttk LabelFrame widget and give the frame a name. The parent container is win, our main window.

The three lines following comment # 2 create label names and place them in the LabelFrame. We are using the important grid layout tool to arrange the labels within the LabelFrame. The column and row properties of this layout manager give us the power to control our GUI layout.

Note

The parent of our labels is the LabelFrame, not the win instance variable of the main window. We can see the beginning of a layout hierarchy here.

The highlighted comment # 3 shows how easy it is to change our layout via the column and row properties. Note how we change the column to 0, and how we layer our labels vertically by numbering the row values sequentially.

Note

The name ttk stands for "themed tk". The tk-themed widget set was introduced in Tk 8.5.

There's more...

In a recipe later in this chapter, we will embed LabelFrame(s) within LabelFrame(s), nesting them to control our GUI layout.

主站蜘蛛池模板: 遵义市| 鄂尔多斯市| 郴州市| 乡城县| 华宁县| 沙坪坝区| 涟源市| 平和县| 三门县| 丰台区| 田林县| 东丰县| 壤塘县| 新安县| 花莲县| 张家界市| 永清县| 瓮安县| 西贡区| 宁化县| 丰都县| 江华| 库伦旗| 伊宁市| 杭锦后旗| 靖安县| 潼南县| 常德市| 汉阴县| 左云县| 敖汉旗| 红桥区| 敦化市| 阿拉善盟| 浑源县| 蕉岭县| 西城区| 博湖县| 上蔡县| 应城市| 辉南县|