PyQt编写Python GUI程序,舍弃Tkinter,来玩易语…
2018-07-12 07:43:22来源:博客园 阅读 ()


许多Python学习者在学习如何创建一个 GUI 应用的时候都感到十分的困难。其中最重要的原因是,他们不知道应该从何下手。大多数的教程都只有文字,但事实上仅仅依靠文字很难学会 GUI 编程,因为 GUI 应用大多数都是基于视觉上的。

这就是我们即将完成的东西:

这是一个简单的 GUI 应用,根据输入的价格(price)和税率(tax rate),计算出最终的价格(final price)。
大多数的教程都试图直接通过Python代码来对 GUI 应用进行布局,但是这样做实在是很费劲。我们将要做的是利用优秀的 QT Designer 工具来对我们的应用进行布局。

不要再用代码来设计界面了。所有的东西都将通过图形界面来搞定。
前提
如果你已经接受了我的建议并且安装了 Anaconda,你应该已经安装好了 PyQt4。如果没有的话,你需要从这里先下载它。

着手
打开 QT Designer。在弹出的窗口中,选择 Main Window,这样它会给你一个空白的画板。

接下来在左侧选择Text Edit:

将Text Edit 拖动到主窗口:

红圈框起来的部分就是定义这个对象的名字的地方。这个名字将是我们通过 Python 代码调用到这个对象的变量名。

我将它取名为price_box,因为我们会在这里输入价格。然后我们需要给这个输入框添加一个 label(按钮),以便让用户更加清楚这个输入框的作用。

我在上图中圈出了 label。把它拖动到主窗口当中来。



对于税率(tax)输入框,我们会使用另外的一个东西。找到spin box:

左侧用圈框起来的部分就是一个spin box。

请记住这将会是你在 Python 代码中调用它的时候会使用到的变量名。

我们可以为我们的spin box 设置一个默认值。我选择将其设置为 20:

你会发现我们也可以设置它的最小值和最大值。不过我并不打算去更改他们。
同样地,我会为它添加一个标签叫做Tax Rate。然后看看我们接下来会用到的圈起来的Push Button:

好的,现在选择Push Button 然后将其拖动到我们的窗口中来。

这个按钮现在显示的是PushButton,这并不是一个很有意义的名字。


然后,我们可以修改真正的显示文字列了:



如果你觉得需要的话,你可以添加一个大标题。这是一个简单的label box 并且将字体加大了。

现在保存你的成果:



编写python代码
Qt 代码是面向对象的,并且简单易学。所有我们添加的组件都是一个对象,并且都拥有自己的方法比如toPlainText()(用来读取输入框中的值)。这让它使用起来非常方便。
这些代码非常有用,每当你想要创建一个新的 PyQt 项目的时候,就在这段代码的基础上添加你自己的代码吧。
这段代码如下:

注意第三行:

你需要在这里填入你先前创建的文件的地址。这个文件将会被内置的函数载入:

让我们大致地看一看这段代码:



你不一定非得要了解这些代码的细节。你只需要在它的基础上继续开发就好了。
下载pyqt_skeleton.py 这个文件,并将它重命名为pyqt_first.py。这是因为我们不想去改动到源文件。然后要做的第一件事就是在代码中导入我们自己的 XML 文件,这个 XML 文件包含了我们的这个 GUI 信息。将下面的这一行:

替换为




我们还没有实现这个函数。所以让我们动手开始写吧。
在MyApp 类中,添加另外一个函数。我们需要先看看整个函数,然后再去了解它的细节:

好了,让我们一行一行的分析上面的代码。
我们现在要做两件事:读取价格和税率,然后计算最终的价格。好了开始吧。请记住,我们要通过我们设定的名字来调用这些组件(这就是我让你不要用默认的通用名称比如box1 的原因,否则的话我们在写代码的时候会很恼火)。


Python


最后运行我们写好的程序:
Python
python pyqt_first.py


好了,这就是一个简单的 PyQt 教程。
如果你还想要体验更多好玩儿的东西,你可以试着用一用别的组件。

标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash