python GUI輸入窗口

  爲了解決 sublime text 下 python 的 raw_input() 函數沒法起效,便萌生了個用 GUI 窗口來獲取輸入的想法,一開始想用 Tkinter,後來想了下仍是用 PyQt 吧,一來代碼量差不到哪裏去,二來 Qt 顯然更美觀一些。封裝成一個模塊 Input.py:python

#!/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(u'GUI 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 模塊就好了。效果以下:app

  

  在輸入框輸入任何字符串後按肯定就能夠返回 Unicode 編碼的 string,在 sublime text 下用 python 開發調試時就不再用擔憂如何方便地進行輸入的問題了。函數

相關文章
相關標籤/搜索