229.md 1.6 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Tk 小部件

> 原文: [https://pythonspot.com/tk-widgets/](https://pythonspot.com/tk-widgets/)

[Tkinter](https://pythonspot.com/tkinter/) 有几个小部件,包括:

*   标签
*   编辑文字
*   图片
*   按钮(之前讨论过)

在本文中,我们将展示如何使用其中的一些 Tkinter 小部件。 请记住,Python 2.x 和 3.x 的 Tkinter 略有不同

W
wizardforcel 已提交
14 15 16
## 标签

要创建标签,我们只需调用 Label()类并将其打包。 padx 和 pady 是水平和垂直填充。
W
wizardforcel 已提交
17

W
wizardforcel 已提交
18
```py
W
wizardforcel 已提交
19 20 21 22 23 24 25 26 27 28
from Tkinter import *

root = Tk()
root.title('Python Tk Examples @ pythonspot.com')
Label(root, text='Python').pack(pady=20,padx=50)

root.mainloop()

```

W
wizardforcel 已提交
29 30 31
## EditText(条目小部件)

要获取用户输入,可以使用条目小部件。
W
wizardforcel 已提交
32

W
wizardforcel 已提交
33
```py
W
wizardforcel 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
from Tkinter import *

root = Tk()
root.title('Python Tk Examples @ pythonspot.com')

var = StringVar()
textbox = Entry(root, textvariable=var)
textbox.focus_set()
textbox.pack(pady=10, padx=10)

root.mainloop()

```

结果:

W
wizardforcel 已提交
50 51
![tk entry](img/37a3257ed2c7f13f0b141e9c9aa72d3e.jpg)

W
wizardforcel 已提交
52
tk 条目
W
wizardforcel 已提交
53

W
wizardforcel 已提交
54 55 56
## 图像

Tk 具有一个小部件来显示图像,即 PhotoImage。 加载图像非常容易:
W
wizardforcel 已提交
57

W
wizardforcel 已提交
58
```py
W
wizardforcel 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
from Tkinter import *
import os

root = Tk()
img = PhotoImage(file="logo2.png")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

```

结果:

W
wizardforcel 已提交
72 73
![python tk image](img/b572dd0f882ff709fb5896b3f7c9905f.jpg)

W
wizardforcel 已提交
74
python tk 图像
W
wizardforcel 已提交
75 76

## GUI 编辑器
W
wizardforcel 已提交
77

W
wizardforcel 已提交
78
Tkinter GUI 编辑器的概述可以在这里找到: [http://wiki.tcl.tk/4056](https://wiki.tcl.tk/4056)
W
wizardforcel 已提交
79 80

[下载 tkinter 示例](/download-tkinter-examples)