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

Widgets – the building blocks of GUI programs

Now that we have our top level or the root window ready, it is time to think over the question: which components should appear in the window? In Tkinter jargon, these components are called widgets.

The syntax that is used to add a widget is as follows:

my_widget = tk.Widget-name (its container window, ** its configuration options)

In the following example ( 1.02.py ), we will add two widgets, a label and a button, to the root container. Also, note how all the widgets are added between the skeleton code that we defined in the first example:

import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="I am a label widget")
button = tk.Button(root, text="I am a button")
label.pack()
button.pack()
root.mainloop()

Running the preceding code(1.02.py) will generate a window with a label and a button widget, as shown in the following screenshot:

The following is a description of the preceding code:

  • This code added a new instance named label for the label widget. The first parameter defined root as its parent or container. The second parameter configured its text option to read  I am a label widget.
  • Similarly, we defined an instance of a Button widget. This is also bound to the root window as its parent.
  • We used the pack() method, which is essentially required to position the label and button widgets within the window. We will discuss the pack() method and several other related concepts when exploring the geometry management task. However, you must note that some sort of geometry specification is essential for the widgets to be displayed.
主站蜘蛛池模板: 湘潭县| 花莲县| 盖州市| 教育| 滦平县| 乌拉特中旗| 阿坝县| 灵武市| 井研县| 肇源县| 凌海市| 三穗县| 九台市| 蒙自县| 焦作市| 休宁县| 通许县| 江永县| 厦门市| 车致| 中方县| 自贡市| 稷山县| 巴林右旗| 青冈县| 偃师市| 翁源县| 江口县| 乐至县| 塔城市| 沂源县| 北安市| 大冶市| 鄂州市| 溧阳市| 兰州市| 舒兰市| 镇江市| 清河县| 焦作市| 繁峙县|