码迷,mamicode.com
首页 > 编程语言 > 详细

python GUI输入窗口

时间:2016-02-20 14:29:30      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:

  为了解决 sublime text 下 python 的 raw_input() 函数无法起效,便萌生了个用 GUI 窗口来获取输入的想法,一开始想用 Tkinter,后来想了下还是用 PyQt 吧,一来代码量差不到哪里去,二来 Qt 显然更美观一些。封装成一个模块 Input.py:

#!/usr/bin/env python
#-*- coding: utf-8 -*-


def getInput(label_str=None):
    ‘‘‘Return the utf-8 string of text that you write in the lineEdit.
        label_str: the string as the prompt of the label in the dialog.‘‘‘
    from PyQt4 import QtGui, QtCore
    import sys

    if label_str == None:
        label_str = u窗口以Unicode编码返回你所输入的信息:
    else:
        label_str = unicode(label_str)

    class MyWindow(QtGui.QDialog):

        input_str = ‘‘

        def __init__(self):
            QtGui.QDialog.__init__(self)
            self.setWindowTitle(uGUI Input)

            self.label = QtGui.QLabel(label_str)
            self.lineEdit = QtGui.QLineEdit()

            self.ok = QtGui.QPushButton(u确定)
            self.connect(self.ok, QtCore.SIGNAL(clicked()), self.getLine)

            self.clean = QtGui.QPushButton(u清空)
            self.connect(self.clean, QtCore.SIGNAL(clicked()), self.cleaning)

            self.cancel = QtGui.QPushButton(u取消)
            self.connect(self.cancel, QtCore.SIGNAL(clicked()), self.quit)

            layout = QtGui.QGridLayout()
            layout.addWidget(self.label, 0, 0, 1, 4)
            layout.addWidget(self.lineEdit, 1, 0, 1, 4)
            layout.addWidget(self.ok, 2, 1, 1, 1)
            layout.addWidget(self.clean, 2, 2, 1, 1)
            layout.addWidget(self.cancel, 2, 3, 1, 1)
            self.setLayout(layout)

            MyWindow.input_str = ‘‘

        def getLine(self):
            MyWindow.input_str = str(self.lineEdit.text().toUtf8())
            self.close()

        def cleaning(self):
            self.lineEdit.setText(‘‘)

        def quit(self):
            MyWindow.input_str = ‘‘
            self.close()

    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    app.exec_()
    return MyWindow.input_str

if __name__ == __main__:
    pre_str = getInput()
    now_str = pre_str.decode(utf-8)
    print type(pre_str), type(now_str)
    print pre_str
    # print long(pre_str)
    # fp = open(now_str + ‘.txt‘, ‘wb+‘)
    # fp.close()

  使用时只需要 import Input,然后使用 Input.getInput(‘xxx‘) 就行了,试了下还是能支持中文的,只需要安装 PyQt4 或者 PyQt5 模块就行了。效果如下:

  技术分享

  在输入框输入任何字符串后按确定就可以返回 Unicode 编码的 string,在 sublime text 下用 python 开发调试时就再也不用担心如何方便地进行输入的问题了。

python GUI输入窗口

标签:

原文地址:http://www.cnblogs.com/Newdawn/p/5203113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!