Tkinter 中的小部件是什么?
Tkinter是 Python 的标准 GUI(图形用户界面)包。 tkinter为我们提供了各种常见的 GUI 元素,我们可以使用它们来构建界面——例如按钮、菜单和各种类型的输入字段和显示区域。我们称这些元素为 Widgets 。
小部件
一般来说,小部件是图形用户界面 (GUI) 的一个元素,它显示/说明信息或为用户提供与操作系统交互的方式。在Tkinter中,小部件是对象;表示按钮、框架等的类的实例。
每个单独的小部件都是一个Python对象。创建小部件时,您必须将其父级作为参数传递给小部件创建函数。唯一的例外是“根”窗口,它是包含其他所有内容且没有父窗口的顶级窗口。
例子 :
Python
from tkinter import *
# create root window
root = Tk()
# frame inside root window
frame = Frame(root)
# geometry method
frame.pack()
# button inside frame which is
# inside root
button = Button(frame, text ='Geek')
button.pack()
# Tkinter event loop
root.mainloop()
输出 :
小部件类
Tkinter 支持下面提到的核心小部件——
Widgets | Description |
---|---|
Label | It is used to display text or image on the screen |
Button | It is used to add buttons to your application |
Canvas | It is used to draw pictures and others layouts like texts, graphics etc. |
ComboBox | It contains a down arrow to select from list of available options |
CheckButton | It displays a number of options to the user as toggle buttons from which user can select any number of options. |
RadiButton | It is used to implement one-of-many selection as it allows only one option to be selected |
Entry | It is used to input single line text entry from user |
Frame | It is used as container to hold and organize the widgets |
Message | It works same as that of label and refers to multi-line and non-editable text |
Scale | It is used to provide a graphical slider which allows to select any value from that scale |
Scrollbar | It is used to scroll down the contents. It provides a slide controller. |
SpinBox | It is allows user to select from given set of values |
Text | It allows user to edit multiline text and format the way it has to be displayed |
Menu | It is used to create all kinds of menu used by an application |
几何管理
创建一个新的小部件并不意味着它会出现在屏幕上。为了显示它,我们需要调用一个特殊的方法: grid 、 pack (上面的例子)或者place 。
Method | Description |
---|---|
pack() | The Pack geometry manager packs widgets in rows or columns. |
grid() | The Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget. |
place() | The Place geometry manager is the simplest of the three general geometry managers provided in Tkinter. It allows you explicitly set the position and size of a window, either in absolute terms, or relative to another window. |