个性化阅读
专注于IT技术分析

用Tkinter在Python中进行GUI的介绍

本文概述

在开始之前, 你应该熟悉Python以学习Tkinter。如果你不熟悉Python, 请查看srcmini的Python入门课程。

介绍

失踪

使用Tkinter在GUI上使用Drone Feed

你们大多数人都编写代码并在命令行终端或IDE(集成开发环境)中运行, 然后代码会根据你期望的结果在终端或IDE本身上产生输出。但是, 如果你希望系统具有精美的用户界面或应用程序(用例), 则需要GUI。

GUI只是桌面应用程序, 它为你提供了一个界面, 该界面可帮助你与计算机进行交互并丰富你向代码提供命令(命令行输入)的经验。它们用于在台式机, 笔记本电脑和其他电子设备等中执行不同的任务。

利用GUI功能的一些应用程序是:

  • 创建一个具有用户界面和功能的计算器, 该计算器可以持久存在。
  • 文本编辑器, 用于编码的IDE位于GUI应用程序上。
  • 数独, 国际象棋, 单人纸牌等。你可以玩的游戏是GUI应用程序。
  • 用于上网的Chrome, Firefox, Microsoft Edge等是GUI应用程序。

另一个有趣的用例是-用于从你的笔记本电脑控制无人机的GUI, 并且该GUI可能具有操纵无人机的按钮以及一个屏幕, 该屏幕可以实时显示无人机捕获的摄像头。

让我们看看Python提供的一些用于开发GUI的框架:

  • PyQT是为Qt应用程序开发框架实现Qt库的最受欢迎的跨平台Python绑定之一。诺基亚主要拥有Qt。目前, PyQT适用于几乎所有操作系统, 例如Unix / Linux, Windows, Mac OSX。它融合了Python和Qt的优点, 并为程序员提供了灵活性, 使其可以通过编写纯python代码来决定是否创建程序或使用Qt Designer创建可视对话框。

  • Kivy用于创建新的用户界面, 并且是OpenGL ES 2加速框架。与PyQt一样, Kivy也支持几乎所有平台, 例如Windows, MacOSX, Linux, Android, iOS。它是一个开放源代码框架, 其工具包中包含20多个预加载的小部件。

  • Jython是Java的Python端口, 可让Python脚本无缝访问本地计算机上的Java类库。

  • WxPython, 最初称为WxWindows(现称为WxWidgets库), 是跨平台GUI库的开源抽象级包装。它被实现为Python扩展模块。使用WxPython, 作为开发人员, 你可以为Windows, Mac OS和Unix创建本机应用程序。

  • PyGUI是用于Unix, Macintosh和Windows的图形应用程序跨平台框架。与其他一些GUI框架相比, PyGUI到目前为止是所有框架中最简单, 最轻便的, 因为API完全与Python同步。PyGUI在GUI平台和Python应用程序之间插入的代码很少。因此, 应用程序的显示通常会显示平台的自然GUI。

最后, 是今天的教程Tkinter讨论的框架!

  • Tkinter通常使用Tk与Python捆绑在一起, 并且是Python的标准GUI框架。它以其简单性和图形用户界面而闻名。它是开源的, 并且在Python许可下可用。

注意:Tkinter预先安装了Python3, 你无需费心安装它。

现在, 让我们在Tkinter的帮助下构建一个非常简单的GUI, 并在流程图的帮助下了解它。

失踪

渲染基本GUI的流程图

让我们分解以上流程图, 了解每个组件正在处理的内容!

  • 首先, 导入关键组件, 即Tkinter模块。

  • 下一步, 使用tkinter.Tk()方法初始化窗口管理器, 并将其分配给变量。此方法创建一个空白窗口, 其顶部具有通常的GUI应该具有的关闭, 最大化和最小化按钮。

  • 然后, 作为可选步骤, 你可以使用window.title(title_of_the_window)重命名窗口的标题。

  • 接下来, 你使用一个称为Label的小部件, 该小部件用于在窗口中插入一些文本。

  • 然后, 你使用Tkinter的几何管理属性pack()来显示所需尺寸的小部件。

  • 最后, 作为最后一步, 使用mainloop()方法显示窗口, 直到你手动将其关闭。它在后端运行无限循环。
import tkinter

window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Welcome to srcmini's Tutorial on Tkinter!").pack()
window.mainloop()

在终端中运行上述代码后, 你将看到类似的输出, 如下所示。

用Tkinter在Python中进行GUI的介绍4

同样, 你可能有一个小部件按钮, GUI会显示一个按钮而不是一些文本(标签)。

import tkinter
window = tkinter.Tk()
window.title("Button GUI")
button_widget = tkinter.Button(window, text="Welcome to srcmini's Tutorial on Tkinter")
button_widget.pack()
tkinter.mainloop()
用Tkinter在Python中进行GUI的介绍5

尽管你已经学会了在Tkinter中使用小部件, 但是让我们找出Tkinter中还有哪些其他小部件以及每个小部件的功能。

小部件

小部件在本质上类似于HTML中的元素。你将在Tkinter中为不同类型的元素找到不同类型的小部件。它们是标准的GUI元素, 并为用户提供按钮, 文本, 菜单和文本框等控件。

让我们了解一下Tkinter中的所有这些小部件以及示例(源代码)。

  • 按钮:按钮小部件具有用于打开/关闭的属性。当用户单击按钮时, 将在Tkinter中触发事件。

    语法:button_widget = tk.Button(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 可以具有各种值, 例如前景和背景色, 字体, 命令(用于函数调用), 图片, 按钮的高度和宽度。

  • 画布:画布用于在GUI中绘制形状, 并支持多种绘制方法。

    语法:canvas_widget = tk.Canvas(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 可以具有各种值, 例如边框宽度, 背景颜色, 窗口小部件的高度和宽度。

  • Checkbutton:Checkbutton记录开/关或真假状态。它使你可以一次选择多个选项, 甚至不用选中它。

    语法:checkbutton_widget = tk.CheckButton(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 当widget在光标下方时, 它可以具有各种值, 例如标题, 文本, 背景和前景色, 字体, 图像等。

  • Entry:Entry小部件用于在GUI中创建输入字段或从用户获取输入文本。

    语法:entry_widget = tk.Entry(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 可以具有各种值, 例如边框宽度, 背景颜色, 按钮的宽度和高度等。

  • 框架:框架在Tkinter中用作容器, 用于对小部件进行分组和充分组织。

    语法:frame_widget = tk.Frame(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 可以具有各种值, 例如border-width, widget的高度和宽度, highlightcolor(颜色为小部件必须重点突出)。

  • 标签:标签用于创建单行小部件, 例如文本, 图像等。

    语法:label_widget = tk.Label(widget, option = placeholder)其中, widget是父窗口/框架的参数, 而option是一个占位符, 可以具有各种值, 例如按钮的字体, 背景颜色, 图像, 宽度和按钮的高度。

你可以在官方Python文档中找到小部件的完整列表。

几何管理

Tkinter中的所有小部件都有一些几何尺寸。通过这些几何尺寸测量, 你可以组织小部件以及整个父框架或父小部件区域。

这里已经介绍了一种几何管理类, 即pack()。

为此, Tkinter为你提供了三个主要的几何管理器类:

  • pack():它以块的方式组织小部件, 并且完全占用了其可用宽度。这是在窗口中显示窗口小部件的常规方法。

  • grid():它将小部件组织成表状结构。你将在本教程的后面部分详细了解它。

  • place():其目的是按照用户在父窗口小部件中的指示将窗口小部件放置在特定位置。

组织布局和小部件

在本教程的这一部分中, 你将同时使用几何图形和小部件, 让我们看看Tkinter的神奇之处。

要在窗口中排列布局, 你将使用Frame小部件类。让我们创建一个简单的程序来查看框架的工作原理。

  • 你将在pack类的帮助下定义两个框架-顶部和底部。 Frame类将有助于在窗口之间创建分隔。基本上, 单个窗口将以Frame的形式复制到顶部和底部两次。
  • 最后, 你将在窗口中创建四个按钮, 每个框架两个。你可以根据需要为按钮命名和着色, 作为参数。
import tkinter

# Let's create the Tkinter window.
window = tkinter.Tk()
window.title("GUI")

# You will first create a division with the help of Frame class and align them on TOP and BOTTOM with pack() method.
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")

# Once the frames are created then you are all set to add widgets in both the frames.
btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack() #'fg or foreground' is for coloring the contents (buttons)

btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()

btn3 = tkinter.Button(bottom_frame, text = "Button3", fg = "purple").pack(side = "left") #'side' is used to left or right align the widgets

btn4 = tkinter.Button(bottom_frame, text = "Button4", fg = "orange").pack(side = "left")

window.mainloop()

让我们运行上面的代码并查看输出。

用Tkinter在Python中进行GUI的介绍6

格网

就像框架一样, 网格是组织小部件的另一种方式。它使用矩阵行列概念。让我们借助下图在网格类和行列概念之间进行类比。

用Tkinter在Python中进行GUI的介绍7

方阵(2×2)

网格主要采用两个参数行和列。如上图所示, 假设00对应第一个按钮, 而01对应第二个按钮。为了并排放置两个按钮, grid将把行和列参数分别设为00和01。

让我们使用checkbutton来了解网格类如何工作。你将定义两个复选按钮, 并为两个按钮指定一些文本。选中按钮的状态将由onvalue和offvalue决定, 而选中按钮的当前状态将由IntVar()跟踪, 后者将存储在单独的变量中。当offvalue = 1和onvalue = 0时, 将选中相应的复选框。

现在进入网格类, 你将传递参数行, 如果row = 0, 则它将按钮放置在第一行中, 如果row = 1, 则将按钮放置在第二行中。

import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
tkinter.Checkbutton(top, text = "Machine Learning", variable = CheckVar1, onvalue = 1, offvalue=0).grid(row=0, sticky=W)
tkinter.Checkbutton(top, text = "Deep Learning", variable = CheckVar2, onvalue = 0, offvalue =1).grid(row=1, sticky=W)
top.mainloop()

让我们运行此代码并查看输出。

用Tkinter在Python中进行GUI的介绍8

让我们再举一个例子来了解网格。在此示例中, 你还将传递一列作为参数以及行。

import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# You will create two text labels namely 'username' and 'password' and and two input labels for them

tkinter.Label(window, text = "Username").grid(row = 0) #'username' is placed on position 00 (row - 0 and column - 0)

# 'Entry' class is used to display the input-field for 'username' text label
tkinter.Entry(window).grid(row = 0, column = 1) # first input-field is placed on position 01 (row - 0 and column - 1)

tkinter.Label(window, text = "Password").grid(row = 1) #'password' is placed on position 10 (row - 1 and column - 0)

tkinter.Entry(window).grid(row = 1, column = 1) #second input-field is placed on position 11 (row - 1 and column - 1)

# 'Checkbutton' class is for creating a checkbutton which will take a 'columnspan' of width two (covers two columns)
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2)                 

window.mainloop()

让我们看一下上面代码的输出!

用Tkinter在Python中进行GUI的介绍9

这不是很神奇吗?它多么简单, 而且看起来与用HTML编写的代码相同。

绑定或命令功能

绑定或命令函数是在事件发生或被触发时调用的函数。

让我们以一个例子来了解绑定函数。

你将定义一个按钮, 单击该按钮将调用一个称为srcmini_Tutorial的函数。此外, 函数srcmini_Tutorial将使用Tkinter!创建带有文本GUI的新标签。

import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# creating a function called srcmini_Tutorial()
def srcmini_Tutorial():
    tkinter.Label(window, text = "GUI with Tkinter!").pack()

tkinter.Button(window, text = "Click Me!", command = srcmini_Tutorial).pack()
window.mainloop()

让我们运行代码并观察输出。

用Tkinter在Python中进行GUI的介绍10

除了通过单击鼠标来调用绑定功能之外, 还可以通过鼠标移动, 鼠标悬停, 单击, 滚动等来调用事件。

现在让我们看一下bind函数, 它为你提供与上述相同的功能。

通过绑定方法的鼠标单击事件

Bind方法为你提供了一种非常简单的方法来实现鼠标单击事件。让我们看一下可以与bind方法一起使用的三个预定义函数。

点击事件分为leftClick, middleClick和rightClick三种类型。

  • bind方法的<Button-1>参数是左键单击事件, 即当你单击左键时, bind方法将调用指定为其第二参数的函数。

  • <Button-2>用于单击鼠标中键

  • <Button-3>右键单击

现在, 你将学习如何根据发生的事件调用特定的函数。

  • 运行以下程序, 然后单击左, 中, 右按钮以调用特定功能。

  • 该函数将使用指定的文本创建一个新标签。
import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

#You will create three different functions for three different events
def left_click(event):
    tkinter.Label(window, text = "Left Click!").pack()

def middle_click(event):
    tkinter.Label(window, text = "Middle Click!").pack()

def right_click(event):
    tkinter.Label(window, text = "Right Click!").pack()

window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)

window.mainloop()

资源

让我们运行上面的代码。

用Tkinter在Python中进行GUI的介绍11

警报框

你可以使用messagebox方法在Tkinter中创建警报框。你也可以使用messasgebox方法创建问题。

在这里, 你将创建一个简单的警报框并创建一个问题。为了生成警报, 你将使用消息框功能showinfo。创建问题时, 将使用askquestion方法, 并根据对问题的回答, 在GUI上输出Label。

import tkinter
import tkinter.messagebox

# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# Let's create a alert box with 'messagebox' function
tkinter.messagebox.showinfo("Alert Message", "This is just a alert message!")

# Let's also create a question for the user and based upon the response [Yes or No Question] display a message.
response = tkinter.messagebox.askquestion("Tricky Question", "Do you love Deep Learning?")

# A basic 'if/else' block where if user clicks on 'Yes' then it returns 1 else it returns 0. For each response you will display a message with the help of 'Label' method.
if response == 1:
    tkinter.Label(window, text = "Yes, offcourse I love Deep Learning!").pack()
else:
    tkinter.Label(window, text = "No, I don't love Deep Learning!").pack()

window.mainloop()

让我们快速运行上面的代码并查看输出。

用Tkinter在Python中进行GUI的介绍12
用Tkinter在Python中进行GUI的介绍13

渲染图像

如果你能够一直遵循到这里, 那么将图像和图标添加到GUI应该是小菜一碟。你需要做的就是使用Tkinter的PhotoImage方法并将file_path作为参数传递给它。

因此, 事不宜迟, 让我们快速编写代码以在GUI上显示图像。

import tkinter

# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")

# In order to display the image in a GUI, you will use the 'PhotoImage' method of Tkinter. It will an image from the directory (specified path) and store the image in a variable.
icon = tkinter.PhotoImage(file = "CNN.png")

# Finally, to display the image you will make use of the 'Label' method and pass the 'image' variriable as a parameter and use the pack() method to display inside the GUI.
label = tkinter.Label(window, image = icon)
label.pack()

window.mainloop()
用Tkinter在Python中进行GUI的介绍14

做得好, 如果你能够继续进行下去!

作为奖励, 你将使用到目前为止获得的所有知识来创建计算器。因此, 让我们以出色的笔记完成本教程。

用Tkinter创建一个计算器

每个GUI应用程序都包含两个步骤。

  • 创建用户界面

  • 向GUI添加功能

让我们开始创建计算器。大部分代码是不言自明的, 并且某些代码行带有解释注释。

from tkinter import *

# Let's create the Tkinter window
window = Tk()

# Then, you will define the size of the window in width(312) and height(324) using the 'geometry' method
window.geometry("312x324")

# In order to prevent the window from getting resized you will call 'resizable' method on the window
window.resizable(0, 0)

#Finally, define the title of the window
window.title("Calcualtor")


# Let's now define the required functions for the Calculator to function properly.

# 1. First is the button click 'btn_click' function which will continuously update the input field whenever a number is entered or any button is pressed it will act as a button click update.
def btn_click(item):
    global expression
    expression = expression + str(item)
    input_text.set(expression)

# 2. Second is the button clear 'btn_clear' function clears the input field or previous calculations using the button "C"
def btn_clear():
    global expression
    expression = ""
    input_text.set("")

# 3. Third and the final function is button equal ("=") 'btn_equal' function which will calculate the expression present in input field. For example: User clicks button 2, + and 3 then clicks "=" will result in an output 5.
def btn_equal():
    global expression
    result = str(eval(expression)) # 'eval' function is used for evaluating the string expressions directly
    # you can also implement your own function to evalute the expression istead of 'eval' function
    input_text.set(result)
    expression = ""

expression = ""
# In order to get the instance of the input field 'StringVar()' is used
input_text = StringVar()

# Once all the functions are defined then comes the main section where you will start defining the structure of the calculator inside the GUI.

# The first thing is to create a frame for the input field
input_frame = Frame(window, width = 312, height = 50, bd = 0, highlightbackground = "black", highlightcolor = "black", highlightthickness = 1)
input_frame.pack(side = TOP)


# Then you will create an input field inside the 'Frame' that was created in the previous step. Here the digits or the output will be displayed as 'right' aligned
input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify = RIGHT)
input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10) # 'ipady' is an internal padding to increase the height of input field


# Once you have the input field defined then you need a separate frame which will incorporate all the buttons inside it below the 'input field'
btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey")
btns_frame.pack()


# The first row will comprise of the buttons 'Clear (C)' and 'Divide (/)'
clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady = 1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)


# The second row will comprise of the buttons '7', '8', '9' and 'Multiply (*)'
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)


# The third row will comprise of the buttons '4', '5', '6' and 'Subtract (-)'
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)
minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)


# The fourth row will comprise of the buttons '1', '2', '3' and 'Addition (+)'
one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1)
plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)


# Finally, the fifth row will comprise of the buttons '0', 'Decimal (.)', and 'Equal To (=)'
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady = 1)
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)


window.mainloop()
用Tkinter在Python中进行GUI的介绍15

总结

恭喜你完成本教程!

根据你从本教程中学到的知识, 你可以制作一些简单的GUI应用程序。你必须学习更多的样​​式以及与GUI中的对象进行交互的方法。

一个有用的练习是尝试开发类似于创建计算器的应用程序, 这将有助于增强你的信心, 并为你提供有关Tkinter可能实现的一切的更全面的想法。

还有很多要讨论的内容, 你可能想探索Tkinter中的类的概念, 你可以参考该文档。

请随时在下面的评论部分中提出与本教程相关的任何问题。

赞(0)
未经允许不得转载:srcmini » 用Tkinter在Python中进行GUI的介绍

评论 抢沙发

评论前必须登录!