如何使用wxPython构建Python GUI应用程序

There are many graphical user interface (GUI) toolkits that you can use with the Python programming language. The big three are Tkinter, wxPython, and PyQt. Each of these toolkits will work with Windo...
摘要由CSDN通过智能技术生成

There are many graphical user interface (GUI) toolkits that you can use with the Python programming language. The big three are Tkinter, wxPython, and PyQt. Each of these toolkits will work with Windows, macOS, and Linux, with PyQt having the additional capability of working on mobile.

您可以将许多图形用户界面(GUI)工具包与Python编程语言一起使用。 前三个是Tkinter,wxPython和PyQt。 这些工具箱均可以在Windows,macOS和Linux上使用,而PyQt具有在移动设备上工作的附加功能。

A graphical user interface is an application that has buttons, windows, and lots of other widgets that the user can use to interact with your application. A good example would be a web browser. It has buttons, tabs, and a main window where all the content loads.

图形用户界面是具有按钮,窗口和许多其他小部件的应用程序,用户可以使用这些小部件与您的应用程序进行交互。 一个很好的例子是网络浏览器。 它具有按钮,选项卡,以及一个加载所有内容的主窗口。

In this article, you’ll learn how to build a graphical user interface with Python using the wxPython GUI toolkit.

在本文中,您将学习如何使用wxPython GUI工具包通过Python构建图形用户界面。

Here are the topics covered:

这里是涉及的主题:

  • Getting Started with wxPython
  • Definition of a GUI
  • Creating a Skeleton Application
  • Creating a Working Application
  • wxPython入门
  • GUI的定义
  • 创建骨架应用程序
  • 创建一个有效的应用程序

Let’s start learning!

让我们开始学习!

Free Bonus: Click here to get access to a chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

免费红利: 单击此处可访问Python技巧的一章:该书通过简单的示例向您展示了Python的最佳实践,您可以立即应用这些示例编写更精美的Pythonic代码。

wxPython入门 (Getting Started With wxPython)

The wxPython GUI toolkit is a Python wrapper around a C++ library called wxWidgets. The initial release of wxPython was in 1998, so wxPython has been around quite a long time. wxPython’s primary difference from other toolkits, such as PyQt or Tkinter, is that wxPython uses the actual widgets on the native platform whenever possible. This makes wxPython applications look native to the operating system that it is running on.

wxPython GUI工具包是一个名为wxWidgets的C ++库的Python包装器。 wxPython的最初版本是在1998年,因此wxPython已经存在了很长时间。 wxPython与其他工具包(例如PyQtTkinter)的主要区别在于,wxPython会尽可能在本机平台上使用实际的小部件。 这使得wxPython应用程序看起来对运行它的操作系统而言是本机的。

PyQt and Tkinter both draw their widgets themselves, which is why they don’t always match the native widgets, although PyQt is very close.

PyQt和Tkinter都自己绘制窗口小部件,这就是为什么它们并不总是与本地窗口小部件匹配的原因,尽管PyQt非常接近。

This is not to say that wxPython does not support custom widgets. In fact, the wxPython toolkit has many custom widgets included with it, along with dozens upon dozens of core widgets. The wxPython downloads page has a section called Extra Files that is worth checking out.

这并不是说wxPython不支持自定义窗口小部件。 实际上,wxPython工具箱包含许多自定义小部件,以及数十个核心小部件。 wxPython 下载页面上有一个名为Extra Files的部分,值得一试。

Here, there is a download of the wxPython Demo package. This is a nice little application that demonstrates the vast majority of the widgets that are included with wxPython. The demo allows a developer to view the code in one tab and run it in a second tab. You can even edit and re-run the code in the demo to see how your changes affect the application.

在这里,有wxPython演示包的下载。 这是一个很好的小应用程序,它演示了wxPython随附的绝大多数小部件。 该演示使开发人员可以在一个选项卡中查看代码并在第二个选项卡中运行它。 您甚至可以在演示中编辑并重新运行代码,以查看您的更改如何影响应用程序。

安装wxPython (Installing wxPython)

You will be using the latest wxPython for this article, which is wxPython 4, also known as the Phoenix release. The wxPython 3 and wxPython 2 versions are built only for Python 2. When Robin Dunn, the primary maintainer of wxPython, created the wxPython 4 release, he deprecated a lot of aliases and cleaned up a lot of code to make wxPython more Pythonic and easier to maintain.

您将在本文中使用最新的wxPython,即wxPython 4 (也称为Phoenix版本)。 wxPython 3和wxPython 2版本仅针对Python 2构建。 wxPython的主要维护者Robin Dunn创建了wxPython 4版本时,他弃用了许多别名并清理了许多代码,以使wxPython更具Pythonic且更易于维护。

You will want to consult the following links if you are migrating from an older version of wxPython to wxPython 4 (Phoenix):

如果要从旧版本的wxPython迁移到wxPython 4(Phoenix),则需要参考以下链接:

The wxPython 4 package is compatible with both Python 2.7 and Python 3.

wxPython 4软件包与Python 2.7和Python 3兼容。

You can now use pip to install wxPython 4, which was not possible in the legacy versions of wxPython. You can do the following to install it on your machine:

现在,您可以使用pip安装wxPython 4,这在wxPython的旧版本中是不可能的。 您可以执行以下操作将其安装在计算机上:

 $ pip install wxpython
$ pip install wxpython

Note: On Mac OS X you will need a compiler installed such as XCode for the install to complete successfully. Linux may also require you to install some dependencies before the pip installer will work correctly.

注意:在Mac OS X上,您需要安装编译器(如XCode)才能成功完成安装。 Linux可能还要求您安装一些依赖项,然后pip安装程序才能正常运行。

For example, I needed to install freeglut3-dev, libgstreamer-plugins-base0.10-dev, and libwebkitgtk-3.0-dev on Xubuntu to get it to install.

例如,我需要在Xubuntu上安装freeglut3-devlibgstreamer-plugins-base0.10-devlibwebkitgtk-3.0-dev才能进行安装。

Fortunately, the error messages that pip displays are helpful in figuring out what is missing, and you can use the prerequisites section on the wxPython Github page to help you find the information you need if you want to install wxPython on Linux.

幸运的是, pip显示的错误消息有助于找出丢失的内容,如果您想在Linux上安装wxPython,可以使用wxPython Github页面上的前提条件部分来查找所需的信息。

There are some Python wheels available for the most popular Linux versions that you can find in the Extras Linux section with both GTK2 and GTK3 versions. To install one of these wheels, you would use the following command:

在适用于GTK2和GTK3版本的Extras Linux部分中,可以找到一些适用于最受欢迎的Linux版本的Python轮子。 要安装这些轮子之一,请使用以下命令:

Be sure you have modified the command above to match your version of Linux.

确保已修改上面的命令以匹配您的Linux版本。

GUI的定义 (Definition of a GUI)

As was mentioned in the introduction, a graphical user interface (GUI) is an interface that is drawn on the screen for the user to interact with.

如引言中所述,图形用户界面(GUI)是在屏幕上绘制的供用户进行交互的界面。

User interfaces have some common components:

用户界面具有一些通用组件:

  • Main window
  • Menu
  • Toolbar
  • Buttons
  • Text Entry
  • Labels
  • 主视窗
  • 菜单
  • 工具列
  • 纽扣
  • 文字输入
  • 标签

All of these items are known generically as widgets. There are many other common widgets and many custom widgets that wxPython supports. A developer will take the widgets and arrange them logically on a window for the user to interact with.

所有这些项目通常称为小部件 。 wxPython支持许多其他常见的小部件和许多自定义小部件。 开发人员将获取这些小部件,并将它们按逻辑排列在一个窗口上,以便用户与之交互。

事件循环 (Event Loops)

A graphical user interface works by waiting for the user to do something. The something is called an event. Events happen when the user types something while your application is in focus or when the user uses their mouse to press a button or other widget.

图形用户界面通过等待用户做某事来工作。 这种事情称为事件 。 当用户在应用程序处于焦点状态时键入某些内容时,或者当用户使用鼠标按下按钮或其他小部件时,就会发生事件。

Underneath the covers, the GUI toolkit is running an infinite loop that is called an event loop. The event loop just waits for events to occur and then acts on those events according to what the developer has coded the application to do. When the application doesn’t catch an event, it effectively ignores that it even happened.

在后台,GUI工具包正在运行一个称为事件循环的无限循环 。 事件循环只是等待事件发生,然后根据开发人员对应用程序进行编码的方式对这些事件进行操作。 当应用程序未捕获事件时,它实际上忽略了事件的发生。

When you are programming a graphical user interface, you will want to keep in mind that you will need to hook up each of the widgets to event handlers so that your application will do something.

在编写图形用户界面时,请记住,您需要将每个小部件都连接到事件处理程序,以便您的应用程序可以执行某些操作。

There is a special consideration that you need to keep in mind when working with event loops: they can be blocked. When you block an event loop, the GUI will become unresponsive and appear to freeze to the user.

使用事件循环时,需要特别注意:它们可以被阻塞。 当您阻止事件循环时,GUI将变得无响应,并且似乎冻结给用户。

Any process that you launch in a GUI that will take longer than a quarter second should probably be launched as a separate thread or process. This will prevent your GUI from freezing and give the user a better user experience.

您在GUI中启动将花费四分之一秒以上的任何进程,应该将其作为单独的线程或进程启动。 这将防止您的GUI冻结,并为用户提供更好的用户体验。

The wxPython framework has special thread-safe methods that you can use to communicate back to your application to let it know that the thread is finished or to give it an update.

wxPython框架具有特殊的线程安全方法,可用于与应用程序进行通信,以使其知道线程已完成或对其进行更新。

Let’s create a skeleton application to demonstrate how events work.

让我们创建一个框架应用程序来演示事件如何工作。

创建骨架应用程序 (Creating a Skeleton Application)

An application skeleton in a GUI context is a user interface with widgets that don’t have any event handlers. These are useful for prototyping. You basically just create the GUI and present it to your stakeholders for sign-off before spending a lot of time on the backend logic.

GUI上下文中的应用程序框架是带有小部件的用户界面,这些小部件没有任何事件处理程序。 这些对于原型制作很有用。 您基本上只是创建GUI,然后将其呈现给您的利益相关者以供签署,然后再在后端逻辑上花费大量时间。

Let’s start by creating a Hello World application with wxPython:

让我们首先使用wxPython创建一个Hello World应用程序:

 import import wx

wx

app app = = wxwx .. AppApp ()
()
frame frame = = wxwx .. FrameFrame (( parentparent == NoneNone , , titletitle == 'Hello World''Hello World' )
)
frameframe .. ShowShow ()
()
appapp .. MainLoopMainLoop ()
()

Note: Mac users may get the following message: This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. If you see this message and you are not running in a virtualenv, then you need to run your application with pythonw instead of python. If you are running wxPython from within a virtualenv, then see the wxPython wiki for the solution.

注意: Mac用户可能会收到以下消息:该程序需要访问屏幕。 请仅在登录Mac主显示屏时使用Python的Framework构建版本运行。 如果看到此消息,并且您没有在virtualenv中运行,则需要使用pythonw而不是python运行应用程序。 如果您是从virtualenv内部运行wxPython,请参阅wxPython Wiki获取解决方案。

In this example, you have two parts: wx.App and the wx.Frame. The wx.App is wxPython’s application object and is required for running your GUI. The wx.App starts something called a .MainLoop(). This is the event loop that you learned about in the previous section.

在此示例中,您分为两部分: wx.Appwx.Framewx.App是wxPython的应用程序对象,是运行GUI所必需的。 wx.App启动一个名为.MainLoop()东西。 这是您在上一节中了解的事件循环。

The other piece of the puzzle is wx.Frame, which will create a window for the user to interact with. In this case, you told wxPython that the frame has no parent and that its title is Hello World. Here is what it looks like when you run the code:

另一个难题是wx.Frame ,它将为用户创建一个与之交互的窗口。 在这种情况下,您告诉wxPython该框架没有父框架,其标题是Hello World 。 这是运行代码时的样子:

wxPython中的Hello World

Note: The application will look different when you run it on Mac or Windows.

注意:在Mac或Windows上运行时,该应用程序看起来会有所不同。

By default, a wx.Frame will include minimize, maximize, and exit buttons along the top. You won’t normally create an application in this manner though. Most wxPython code will require you to subclass the wx.Frame and other widgets so that you can get the full power of the toolkit.

默认情况下, wx.Frame将在顶部包括最小化,最大化和退出按钮。 但是,您通常不会以这种方式创建应用程序。 大多数wxPython代码将要求您将wx.Frame和其他小部件作为子类,以便获得该工具包的全部功能。

Let’s take a moment and rewrite your code as a class:

让我们花点时间将您的代码重写为一个类:

You can use this code as a template for your application. However, this application doesn’t do very much, so let’s take a moment to learn a little about some of the other widgets you could add.

您可以将此代码用作应用程序的模板。 但是,该应用程序的功能不是很多,因此让我们花一点时间来学习一些您可以添加的其他小部件。

小部件 (Widgets)

The wxPython toolkit has more than one hundred widgets to choose from. This allows you to create rich applications, but it can also be daunting trying to figure out which widget to use. This is why the wxPython Demo is helpful, as it has a search filter that you can use to help you find the widgets that might apply to your project.

wxPython工具箱有一百多种小部件可供选择。 这使您可以创建功能丰富的应用程序,但是尝试弄清楚要使用哪个窗口小部件也可能令人生畏。 这就是wxPython演示之所以有用的原因,因为它具有一个搜索过滤器,可用于帮助您找到可能适用于您的项目的小部件。

Most GUI applications allow the user to enter some text and press a button. Let’s go ahead and add those widgets:

大多数GUI应用程序允许用户输入一些文本并按下按钮。 让我们继续添加这些小部件:

 import import wx

wx

class class MyFrameMyFrame (( wxwx .. FrameFrame ):    
    ):    
    def def __init____init__ (( selfself ):
        ):
        supersuper ()() .. __init____init__ (( parentparent == NoneNone , , titletitle == 'Hello World''Hello World' )
        )
        panel panel = = wxwx .. PanelPanel (( selfself )

        )

        selfself .. text_ctrl text_ctrl = = wxwx .. TextCtrlTextCtrl (( panelpanel , , pospos == (( 55 , , 55 ))
        ))
        my_btn my_btn = = wxwx .. ButtonButton (( panelpanel , , labellabel == 'Press Me''Press Me' , , pospos == (( 55 , , 5555 ))

        ))

        selfself .. ShowShow ()

()

if if __name__ __name__ == == '__main__''__main__' :
    :
    app app = = wxwx .. App
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值