欢迎访问宙启技术站
智能推送

Python函数编程实例:创建图形化用户界面(GUI)

发布时间:2023-06-24 01:27:23

Python函数编程是Python语言重要的编程范式之一。其优点在于可以实现程序的模块化和代码的重用性,并且可以将代码逻辑清晰地分层。GUI(Graphical User Interface,图形化用户界面)对于一些软件系统来说,往往是必不可少的一个部分;掌握Python函数编程顺便学习Python GUI编程,能够为程序员带来更高的代码效率和更良好的用户体验。

一.Python GUI编程

在Python GUI编程中,Tkinter是一种常用的Python图形化界面编程库。通过Tkinter库,可以很方便地创建各种GUI界面,比如按钮、标签、文本框、下拉列表、菜单、画布等等。Tkinter库是Python标准库中的一部分,因此当安装Python时,Tkinter也已经被安装了。

二.创建一个简单的GUI界面

由于Tkinter已经安装了,因此在Python中引入Tkinter只需要使用import语句即可:

import tkinter as tk

from tkinter import messagebox

'''创建GUI界面'''

root = tk.Tk()   # 生成一个窗口框体

'''以下是界面的组件配置'''

# 生成一个标签

label = tk.Label(root, text='这是一个展示窗口', font=('微软雅黑', 15), bg='lightgreen', fg='blue')

label.pack(padx=20, pady=30)     # 设置标签的外观,使其居中对齐

# 生成一个按钮,并为其设置回调函数

def button_callback():

    messagebox.showinfo('消息提示', '你点击了这个按钮')

button = tk.Button(root, text='我是一个按钮', font=('微软雅黑', 15), bg='purple', fg='white', command=button_callback)

button.pack(side='bottom', padx=20, pady=30)   # 设置按钮的位置

'''开启循环'''

root.mainloop()  # 进入循环,开启界面

以上代码是一个展示窗口和一个按钮的GUI界面。其中,展示窗口是一个标签,通过Tkinter库的Label对象生成。按钮是一个按钮,通过Tkinter库的Button对象生成,设置了回调函数button_callback()。

三.一个实际应用 - 图像处理

下面我们来看一个复杂点的例子。考虑一个图像处理的应用,该应用会将用户选择的图像进行灰度化,并对图像进行一个简单的平滑处理(均值滤波)。该实例主要运用了Python的函数编程的一些思想,让代码具有较好的可重用性。

# -*- coding: utf-8 -*-

import tkinter as tk

from tkinter import filedialog

from tkinter import messagebox

import cv2

import numpy as np

'''生成一个图像处理的类,该类将图像处理的方法封装起来'''

class ImageProcessor:

    '''对图像进行灰度化的方法'''

    def to_grayscale(self, image):

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        return gray

    '''对图像进行平滑处理的方法'''

    def smooth(self, image, size=3):

        kernel = np.ones((size, size), np.float32) / (size * size)

        dst = cv2.filter2D(image, -1, kernel)

        return dst

'''生成一个GUI界面'''

root = tk.Tk()   # 生成一个窗口框体

root.geometry('500x300')  # 设置窗口的大小

'''界面的组件设计'''

label1 = tk.Label(root, text='图像选择', font=('微软雅黑', 15), bg='lightgreen', fg='blue')

label1.place(x=20, y=20)

# 选择图像的文件名

filename = ''

def open_file():

    global filename

    filename = filedialog.askopenfilename()

    print('打开文件:%s' % filename)

    messagebox.showinfo('消息提示', '你选择了一个图像文件')

button1 = tk.Button(root, text='打开文件', font=('微软雅黑', 15), bg='purple', fg='white', command=open_file)

button1.place(x=30, y=70)

# 显示选择的图像

canvas = tk.Canvas(root, width=300, height=300, bg='white', bd=1, relief='solid')

canvas.place(x=170, y=20)

def display_image():

    if len(filename) <= 0:

        messagebox.showerror('错误提示', '尚未选择图像文件')

    else:

        image = cv2.imread(filename)

        ih, iw = image.shape[:2]

        if ih > 300 or iw > 300:

            image = cv2.resize(image, (300, 300))

        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        canvas.bind('<Button-1>', lambda e : to_grayscale(image))

        canvas.bind('<Button-2>', lambda e: to_smooth(image))

        h, w = image.shape[:2]

        bitmap = tk.BitmapImage(master=canvas, data=image, foreground='white')

        canvas.create_image(0, 0, image=bitmap, anchor=tk.NW)

def to_grayscale(image):

    # 实例化一个图像处理对象

    processor = ImageProcessor()

    # 调用图像处理方法

    gray = processor.to_grayscale(image)

    gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)

    # 将图像显示到画布中

    bitmap = tk.BitmapImage(master=canvas, data=gray, foreground='white')

    canvas.create_image(0, 0, image=bitmap, anchor=tk.NW)

def to_smooth(image):

    # 实例化一个图像处理对象

    processor = ImageProcessor()

    # 调用图像处理方法

    smoothed = processor.smooth(image, size=5)

    smoothed = cv2.cvtColor(smoothed, cv2.COLOR_BGR2RGB)

    # 将图像显示到画布中

    bitmap = tk.BitmapImage(master=canvas, data=smoothed, foreground='white')

    canvas.create_image(0, 0, image=bitmap, anchor=tk.NW)

button2 = tk.Button(root, text='显示图像', font=('微软雅黑', 15), bg='blue', fg='white', command=display_image)

button2.place(x=30, y = 130)

'''进入循环'''

root.mainloop()  # 进入循环,开启界面

在这个例子中,我们通过生成一个图像处理的类(ImageProcessor)来封装对图像进行灰度化和平滑的方法,这样做的好处是可以实现代码的重用性,增强了程序的可读性和可维护性。在GUI界面方面,通过使用Tkinter对象的Canvas,我们能够快速地把图像显示到画布上。

四.总结

在这篇文章中,我们简单介绍了Python函数编程以及Python图形化GUI编程。我们通过两个例子来说明如何用Python编写一个GUI程序,并对它加入一些函数编程的特点,从而增强程序的可读性和可维护性。尽管Python的GUI编程有一定的限制,例如它的事件驱动机制没有如Java那样强大,但是Python仍然是很好的一个编程语言,可以处理各种类型的任务,包括我们常用的图像处理任务。