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

Ways to create widgets

There are two ways to create widgets in Tkinter.

The first way involves creating a widget in one line and then adding the pack() method (or other geometry managers) in the next line, as follows:

my_label = tk.Label(root, text="I am a label widget")
my_label.pack()

Alternatively, you can write both the lines together, as follows:

tk.Label(root, text="I am a label widget").pack()

You can either save a reference to the widget created ( my_label, as in the first example), or create a widget without keeping any reference to it (as demonstrated in the second example).

You should ideally keep a reference to the widget in case the widget has to be accessed later on in the program. For instance, this is useful in case you need to call one of its internal methods or for its content modification. If the widget state is supposed to remain static after its creation, you need not keep a reference to the widget.

Note that calls to pack() (or other geometry managers) always return None. So, consider a situation where you create a widget, and add a geometry manager (say, pack()) on the same line, as follows: my_label = tk.Label(...).pack(). In this case, you are not creating a reference to the widget. Instead, you are creating a None type object for the my_label variable. So, when you later try to modify the widget through the reference, you get an error because you are actually trying to work on a None type object. If you need a reference to a widget, you must create it on one line and then specify its geometry (like pack()) on the second line, as follows:
my_label = tk.Label(...)
my_label.pack()
This is one of the most common mistakes committed by beginners.
主站蜘蛛池模板: 曲麻莱县| 沾化县| 长顺县| 巢湖市| 杭锦旗| 金门县| 芜湖市| 长岭县| 东城区| 甘肃省| 灵璧县| 呈贡县| 高青县| 昌黎县| 芦山县| 溆浦县| 静安区| 大宁县| 子长县| 资兴市| 祁连县| 宜都市| 西和县| 安丘市| 墨竹工卡县| 宁夏| 嘉荫县| 健康| 荆州市| 南木林县| 望奎县| 渝中区| 磐石市| 镇江市| 绥芬河市| 龙海市| 宁津县| 德钦县| 青海省| 民乐县| 黑山县|