Python 简明教程
Python - GUI Programming
Python 为开发图形用户界面 (GUI) 提供了各种选项。最重要的功能如下。
Python provides various options for developing graphical user interfaces (GUIs). The most important features are listed below.
-
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look at this option in this chapter.
-
wxPython − This is an open-source Python interface for wxWidgets GUI toolkit. You can find a complete tutorial on WxPython here.
-
PyQt − This is also a Python interface for a popular cross-platform Qt GUI library. TutorialsPoint has a very good tutorial on PyQt5 here.
-
PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library. The complete PyGTK tutorial is available here.
-
PySimpleGUI − PySimpleGui is an open source, cross-platform GUI library for Python. It aims to provide a uniform API for creating desktop GUIs based on Python’s Tkinter, PySide and WxPython toolkits. For a detaile PySimpleGUI tutorial, click here.
-
Pygame − Pygame is a popular Python library used for developing video games. It is free, open source and cross-platform wrapper around Simple DirectMedia Library (SDL). For a comprehensive tutorial on Pygame, visit this link.
-
Jython − Jython is a Python port for Java, which gives Python scripts seamless access to the Java class libraries on the local machinehttp: //www.jython.org.
网上还能找到许多其他可用的接口。
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter 是 Python 的标准 GUI 库。Python 与 Tkinter 相结合,提供了一种快速且简单的方法来创建 GUI 应用程序。Tkinter 为 Tk GUI 工具包提供了一个功能强大的面向对象接口。
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
tkinter 包包括以下模块 −
The tkinter package includes following modules −
-
Tkinter − Main Tkinter module.
-
tkinter.colorchooser − Dialog to let the user choose a color.
-
tkinter.commondialog − Base class for the dialogs defined in the other modules listed here.
-
tkinter.filedialog − Common dialogs to allow the user to specify a file to open or save.
-
tkinter.font − Utilities to help work with fonts.
-
tkinter.messagebox − Access to standard Tk dialog boxes.
-
tkinter.scrolledtext − Text widget with a vertical scroll bar built in.
-
tkinter.simpledialog − Basic dialogs and convenience functions.
-
tkinter.ttk − Themed widget set introduced in Tk 8.5, providing modern alternatives for many of the classic widgets in the main tkinter module.
使用 Tkinter 创建 GUI 应用程序是一项简单的任务。你所需要做的就是执行以下步骤。
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps.
-
Import the Tkinter module.
-
Create the GUI application main window.
-
Add one or more of the above-mentioned widgets to the GUI application.
-
Enter the main event loop to take action against each event triggered by the user.
Example
# note that module name has changed from Tkinter in Python 2
# to tkinter in Python 3
import tkinter
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
它会创建一个如下窗口 -
This would create a following window −
当程序变得更复杂时,使用面向对象编程方法会让代码更具条理。
When the program becomes more complex, using an object-oriented programming approach makes the code more organized.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
app = App()
app.mainloop()
Tkinter Widgets
Tkinter 提供各种控件,如按钮、标签和 GUI 应用程序中使用的文本框。这些控件通常称为微件。
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.
Tkinter 中当前有 15 种微件。我们以下表的形式介绍这些微件并进行简要说明 -
There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table −
让我们详细了解这些微件。
Let us study these widgets in detail.
Standard Attributes
让我们看看如何指定一些常见属性,如大小、颜色和字体。
Let us look at how some of the common attributes, such as sizes, colors and fonts are specified.
让我们简要地研究一下 -
Let us study them briefly −
Geometry Management
所有 Tkinter 微件都可以访问特定的几何管理方法,其目的是在父微件区域中组织微件。Tkinter 揭示了以下几何管理器类:pack、grid 和 place。
All Tkinter widgets have access to the specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place.
-
The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent widget.
-
The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
-
The place() Method − This geometry manager organizes widgets by placing them in a specific position in the parent widget.
让我们简要地研究一下几何管理方法 -
Let us study the geometry management methods briefly −
SimpleDialog
tkinter 包中的 simpledialog 模块包括一个对话框类和通过模式对话框接受用户输入的便捷函数。它包含一个标签、一个小组件和两个按钮(确定和取消)。这些函数如下 -
The simpledialog module in tkinter package includes a dialog class and convenience functions for accepting user input through a modal dialog. It consists of a label, an entry widget and two buttons Ok and Cancel. These functions are −
-
askfloat(title, prompt, **kw) − Accepts a floating point number.
-
askinteger(title, prompt, **kw) − Accepts an integer input.
-
askstring(title, prompt, **kw) − Accepts a text input from the user.
以上三个函数提供提示用户输入所需类型值的对话框。如果按下确定,则返回输入,如果按下取消,则返回无。
The above three functions provide dialogs that prompt the user to enter a value of the desired type. If Ok is pressed, the input is returned, if Cancel is pressed, None is returned.
askinteger
from tkinter.simpledialog import askinteger
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def show():
num = askinteger("Input", "Input an Integer")
print(num)
B = Button(top, text ="Click", command = show)
B.place(x=50,y=50)
top.mainloop()
它将生成以下 output −
It will produce the following output −
askfloat
from tkinter.simpledialog import askfloat
from tkinter import *
top = Tk()
top.geometry("100x100")
def show():
num = askfloat("Input", "Input a floating point number")
print(num)
B = Button(top, text ="Click", command = show)
B.place(x=50,y=50)
top.mainloop()
它将生成以下 output −
It will produce the following output −
askstring
from tkinter.simpledialog import askstring
from tkinter import *
top = Tk()
top.geometry("100x100")
def show():
name = askstring("Input", "Enter you name")
print(name)
B = Button(top, text ="Click", command = show)
B.place(x=50,y=50)
top.mainloop()
它将生成以下 output −
It will produce the following output −
The FileDialog Module
Tkinter 包中的 filedialog 模块包括一个 FileDialog 类。它还定义了能使用户执行打开文件、保存文件和打开目录活动的便捷函数。
The filedialog module in Tkinter package includes a FileDialog class. It also defines convenience functions that enable the user to perform open file, save file, and open directory activities.
-
filedialog.asksaveasfilename()
-
filedialog.asksaveasfile()
-
filedialog.askopenfilename()
-
filedialog.askopenfile()
-
filedialog.askdirectory()
-
filedialog.askopenfilenames()
-
filedialog.askopenfiles()
askopenfile
此功能允许用户从文件系统中选择所需文件。文件对话框窗口具有“打开”和“取消”按钮。按确定时返回文件名及其路径,按取消时返回无。
This function lets the user choose a desired file from the filesystem. The file dialog window has Open and Cancel buttons. The file name along with its path is returned when Ok is pressed, None if Cancel is pressed.
from tkinter.filedialog import askopenfile
from tkinter import *
top = Tk()
top.geometry("100x100")
def show():
filename = askopenfile()
print(filename)
B = Button(top, text ="Click", command = show)
B.place(x=50,y=50)
top.mainloop()
它将生成以下 output −
It will produce the following output −
ColorChooser
Tkinter 包中包含的 colorchooser 模块具有让用户通过颜色对话框选择所需颜色对象的功能。askcolor() 函数显示带有一些预定义颜色色块的颜色对话框,还可以通过设置 RGB 值来选择定制颜色。此对话框返回所选颜色的 RGB 值和十六进制值的元组。
The colorchooser module included in tkinter package has the feature of letting the user choose a desired color object through the color dialog. The askcolor() function presents with the color dialog with predefined color swatches and facility to choose custome color by setting RGB values. The dialog returns a tuple of RGB values of chosen color as well as its hex value.
from tkinter.colorchooser import askcolor
from tkinter import *
top = Tk()
top.geometry("100x100")
def show():
color = askcolor()
print(color)
B = Button(top, text ="Click", command = show)
B.place(x=50,y=50)
top.mainloop()
它将生成以下 output −
It will produce the following output −
((0, 255, 0), '#00ff00')
ttk module
ttk 一词来自 Tk 主题小部件。ttk 模块在 Tk 8.5 及更高版本中引入。它提供了其他好处,包括 X11 下的抗锯齿字体渲染和窗口透明度。它为 Tkinter 提供主题和样式支持。
The term ttk stands from Tk Themed widgets. The ttk module was introduced with Tk 8.5 onwards. It provides additional benefits including anti-aliased font rendering under X11 and window transparency. It provides theming and styling support for Tkinter.
ttk 模块捆绑了 18 个小部件,其中 12 个已经存在于 Tkinter 中。导入 ttk 会用新的小部件覆盖这些小部件,新的小部件设计为在所有平台上具有更好、更现代的外观。
The ttk module comes bundled with 18 widgets, out of which 12 are already present in Tkinter. Importing ttk over-writes these widgets with new ones which are designed to have a better and more modern look across all platforms.
ttk 中的 6 个新小部件是 Combobox、Separator、Sizegrip、Treeview、Notebook 和 ProgressBar。
The 6 new widgets in ttk are, the Combobox, Separator, Sizegrip, Treeview, Notebook and ProgressBar.
要覆盖基本 Tk 小部件,导入应遵循 Tk 导入−
To override the basic Tk widgets, the import should follow the Tk import −
from tkinter import *
from tkinter.ttk import *
原始 Tk 小部件会自动被 tkinter.ttk 小部件替换。它们是 Button、Checkbutton、Entry、Frame、Label、LabelFrame、Menubutton、PanedWindow、Radiobutton、Scale 和 Scrollbar。
The original Tk widgets are automatically replaced by tkinter.ttk widgets. They are Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar.
新的小部件在各个平台上带来更好的外观和使用体验;不过,替换的小部件并不完全兼容。主要区别在于小部件选项(如“fg”、“bg”和与小部件样式相关的其他选项)不再存在于 Ttk 小部件中。相反,使用 ttk.Style 类以获得改进的样式效果。
New widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. The main difference is that widget options such as "fg", "bg" and others related to widget styling are no longer present in Ttk widgets. Instead, use the ttk.Style class for improved styling effects.
ttk 模块中的新小部件有−
The new widgets in ttk module are −
-
Notebook − This widget manages a collection of "tabs" between which you can swap, changing the currently displayed window.
-
ProgressBar − This widget is used to show progress or the loading process through the use of animations.
-
Separator − Used to separate different widgets using a separator line.
-
Treeview − This widget is used to group together items in a tree-like hierarchy. Each item has a textual label, an optional image, and an optional list of data values.
-
ComboBox − Used to create a dropdown list of options from which the user can select one.
-
Sizegrip − Creates a little handle near the bottom-right of the screen, which can be used to resize the window.
Combobox Widget
Python ttk Combobox 呈现一个包含选项的下拉列表,一次显示一个选项。它是 Entry 小部件的子类。因此,它从 Entry 类继承了许多选项和方法。
The Python ttk Combobox presents a drop down list of options and displays them one at a time. It is a sub class of the widget Entry. Hence it inherits many options and methods from the Entry class.
Syntax
from tkinter import ttk
Combo = ttk.Combobox(master, values.......)
get() 函数用于检索 Combobox 的当前值。
The get() function to retrieve the current value of the Combobox.
Example
from tkinter import *
from tkinter import ttk
top = Tk()
top.geometry("200x150")
frame = Frame(top)
frame.pack()
langs = ["C", "C++", "Java",
"Python", "PHP"]
Combo = ttk.Combobox(frame, values = langs)
Combo.set("Pick an Option")
Combo.pack(padx = 5, pady = 5)
top.mainloop()
它将生成以下 output −
It will produce the following output −
Progressbar
ttk ProgressBar 小部件及其如何用于创建加载屏幕或显示当前任务的进度。
The ttk ProgressBar widget, and how it can be used to create loading screens or show the progress of a current task.
Parameters
-
Parent − The container in which the ProgressBar is to be placed, such as root or a Tkinter frame.
-
Orient − Defines the orientation of the ProgressBar, which can be either vertical of horizontal.
-
Length − Defines the width of the ProgressBar by taking in an integer value.
-
Mode − There are two options for this parameter, determinate and indeterminate.
Example
下面给出的代码创建一个具有三个按钮的进度条,这些按钮链接到三个不同的函数。
The code given below creates a progressbar with three buttons which are linked to three different functions.
第一个函数将进度条中的“值”或“进度”增加 20。这是通过 step() 函数完成的,该函数采用整数值来更改进度量。(默认为 1.0)
The first function increments the "value" or "progress" in the progressbar by 20. This is done with the step() function which takes an integer value to change progress amount. (Default is 1.0)
第二个函数将进度条中的“值”或“进度”减少 20。
The second function decrements the "value" or "progress" in the progressbar by 20.
第三个函数打印进度条中当前的进度级别。
The third function prints out the current progress level in the progressbar.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
frame= ttk.Frame(root)
def increment():
progressBar.step(20)
def decrement():
progressBar.step(-20)
def display():
print(progressBar["value"])
progressBar= ttk.Progressbar(frame, mode='determinate')
progressBar.pack(padx = 10, pady = 10)
button= ttk.Button(frame, text= "Increase", command= increment)
button.pack(padx = 10, pady = 10, side = tk.LEFT)
button= ttk.Button(frame, text= "Decrease", command= decrement)
button.pack(padx = 10, pady = 10, side = tk.LEFT)
button= ttk.Button(frame, text= "Display", command= display)
button.pack(padx = 10, pady = 10, side = tk.LEFT)
frame.pack(padx = 5, pady = 5)
root.mainloop()
它将生成以下 output −
It will produce the following output −
Notebook
Tkinter ttk 模块有一个新的有用控件,称为 Notebook。它是一个容器(例如框架)的集合,其中包含许多子项小部件。
Tkinter ttk module has a new useful widget called Notebook. It is a of collection of of containers (e.g frames) which have many widgets as children inside.
每个“选项卡”或“窗口”都有一个与其关联的选项卡 ID,用于确定要切换到哪个选项卡。
Each "tab" or "window" has a tab ID associated with it, which is used to determine which tab to swap to.
您可以像在常规文本编辑器上一样在这些容器之间切换。
You can swap between these containers like you would on a regular text editor.
Example
在此示例中,以两种不同的方式将 3 个窗口添加到我们的 Notebook 小部件。第一种方法涉及 add() 函数,它只是将一个新选项卡附加到末尾。另一种方法是 insert() 函数,可用于将选项卡添加到特定位置。
In this example, add 3 windows to our Notebook widget in two different ways. The first method involves the add() function, which simply appends a new tab to the end. The other method is the insert() function which can be used to add a tab to a specific position.
add() 函数需要一个必需的参数,即要添加的容器小部件,其余的是可选参数,例如文本(作为选项卡标题显示的文本)、图像和复合。
The add() function takes one mandatory parameter which is the container widget to be added, and the rest are optional parameters such as text (text to be displayed as tab title), image and compound.
insert() 函数需要一个 tab_id,它定义应插入其位置。tab_id 可以是索引值,也可以是字符串文字,如“end”,它将附加到末尾。
The insert() function requires a tab_id, which defines the location where it should be inserted. The tab_id can be either an index value or it can be string literal like "end", which will append it to the end.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
nb = ttk.Notebook(root)
# Frame 1 and 2
frame1 = ttk.Frame(nb)
frame2 = ttk.Frame(nb)
label1 = ttk.Label(frame1, text = "This is Window One")
label1.pack(pady = 50, padx = 20)
label2 = ttk.Label(frame2, text = "This is Window Two")
label2.pack(pady = 50, padx = 20)
frame1.pack(fill= tk.BOTH, expand=True)
frame2.pack(fill= tk.BOTH, expand=True)
nb.add(frame1, text = "Window 1")
nb.add(frame2, text = "Window 2")
frame3 = ttk.Frame(nb)
label3 = ttk.Label(frame3, text = "This is Window Three")
label3.pack(pady = 50, padx = 20)
frame3.pack(fill= tk.BOTH, expand=True)
nb.insert("end", frame3, text = "Window 3")
nb.pack(padx = 5, pady = 5, expand = True)
root.mainloop()
它将生成以下 output −
It will produce the following output −
Treeview
Treeview 小部件用于以表格或层次结构方式显示项目。它支持诸如为项目创建行和列以及允许项目也有子项的功能,从而形成层次结构。
The Treeview widget is used to display items in a tabular or hierarchical manner. It has support for features like creating rows and columns for items, as well as allowing items to have children as well, leading to a hierarchical format.
Example
在此示例中,我们将创建一个简单的 Treeview ttk 小部件并向其中填写一些数据。我们已经在列表中存储了一些数据,这些数据将在 read_data() 函数中读取并添加到 Treeview 小部件中。
In this example we will create a simple Treeview ttk Widget and fill in some data into it. We have some data already stored in a list which will be reading and adding to the Treeview widget in our read_data() function.
我们首先需要定义列名的列表/元组。我们省略了列“名称”,因为已经存在一个具有空白名称的(默认)列。
We first need to define a list/tuple of column names. We have left out the column "Name" because there already exists a (default) column with a blank name.
然后,我们将该列表/元组分配给 Treeview 中的 columns 选项,然后定义“标题”,其中列是实际的列,而标题只是小部件显示时出现的列的标题。我们给每一列一个名称。“#0”是默认列的名称。
We then assign that list/tuple to the columns option in Treeview, followed by defining the "headings", where the column is the actual column, whereas the heading is just the title of the column that appears when the widget is displayed. We give each a column a name. "#0" is the name of the default column.
tree.insert() 函数具有以下参数 −
The tree.insert() function has the following parameters −
-
Parent − which is left as an empty string if there is none.
-
Position − where we want to add the new item. To append, use tk.END
-
Iid − which is the item ID used to later track the item in question.
-
Text − to which we will assign the first value in the list (the name).
值,我们将传递从列表中获取的其他 2 个值。
Value we will pass the the other 2 values we obtained from the list.
The Complete Code
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import simpledialog
root = tk.Tk()
data = [
["Bobby",26,20000],
["Harrish",31,23000],
["Jaya",18,19000],
["Mark",22, 20500],
]
index=0
def read_data():
for index, line in enumerate(data):
tree.insert('', tk.END, iid = index,
text = line[0], values = line[1:])
columns = ("age", "salary")
tree= ttk.Treeview(root, columns=columns ,height = 20)
tree.pack(padx = 5, pady = 5)
tree.heading('#0', text='Name')
tree.heading('age', text='Age')
tree.heading('salary', text='Salary')
read_data()
root.mainloop()
它将生成以下 output −
It will produce the following output −
Sizegrip
Sizegrip 小组件基本上是一个小箭头式控件,通常放置在屏幕的右下角。将 Sizegrip 拖动到屏幕上也能调整其所连接容器的大小。
The Sizegrip widget is basically a small arrow-like grip that is typically placed at the bottom-right corner of the screen. Dragging the Sizegrip across the screen also resizes the container to which it is attached to.
Example
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry("100x100")
frame = ttk.Frame(root)
label = ttk.Label(root, text = "Hello World")
label.pack(padx = 5, pady = 5)
sizegrip = ttk.Sizegrip(frame)
sizegrip.pack(expand = True, fill = tk.BOTH, anchor = tk.SE)
frame.pack(padx = 10, pady = 10, expand = True, fill = tk.BOTH)
root.mainloop()
它将生成以下 output −
It will produce the following output −
Separator
ttk Separator 小组件是一个非常简单的组件,它只有一个用途,就是通过在小组件之间绘制线条来协助将小组件“分离”成组/分区。我们可以将此线条(分隔符)的方向更改为水平或垂直,并更改其长度/高度。
The ttk Separator widget is a very simple widget, that has just one purpose and that is to help "separate" widgets into groups/partitions by drawing a line between them. We can change the orientation of this line (separator) to either horizontal or vertical, and change its length/height.
Syntax
separator = ttk.Separator(parent, **options)
“orient”,可以是 tk.VERTICAL 或 tk.HORIZTONAL,分别用于垂直分隔符和水平分隔符。
The "orient", which can either be tk.VERTICAL or tk.HORIZTONAL, for a vertical and horizontal separator respectively.
Example
这里我们创建了两个 Label 小组件,然后在它们之间创建了一个水平分隔符。
Here we have created two Label widgets, and then created a Horizontal Separator between them.
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry("200x150")
frame = ttk.Frame(root)
label = ttk.Label(frame, text = "Hello World")
label.pack(padx = 5)
separator = ttk.Separator(frame,orient= tk.HORIZONTAL)
separator.pack(expand = True, fill = tk.X)
label = ttk.Label(frame, text = "Welcome To TutorialsPoint")
label.pack(padx = 5)
frame.pack(padx = 10, pady = 50, expand = True, fill = tk.BOTH)
root.mainloop()
它将生成以下 output −
It will produce the following output −