229.md 1.7 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
# Tk 小部件

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

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

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

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

**相关课程**

*   [带有 Tkinter 的 Python 桌面应用](https://gum.co/ErLc)

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

```
from Tkinter import *

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

root.mainloop()

```

**EditText(条目小部件)** 要获取用户输入,可以使用条目小部件。

```
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()

```

结果:

![tk entry](img/37a3257ed2c7f13f0b141e9c9aa72d3e.jpg) tk entry

**图像** Tk 具有一个小部件来显示图像,即 PhotoImage。 加载图像非常容易:

```
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()

```

结果:

![python tk image](img/b572dd0f882ff709fb5896b3f7c9905f.jpg) python tk image

**GUI 编辑器** Tkinter GUI 编辑器的概述可以在这里找到: [http://wiki.tcl.tk/4056](https://wiki.tcl.tk/4056)

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