【问题标题】:Blank value returned for the pyqt4 lineEdit为 pyqt4 行返回的空白值编辑
【发布时间】:2017-03-01 07:54:15
【问题描述】:

如果这是一个简单/愚蠢的错误或已经得到解答,我深表歉意,我对编程很陌生,我正在自学。这是我在stackoverflow中的第一个问题,所以如果您需要更多信息或者我的问题不清楚,请告诉我。

我的代码无法检索我在 lineEdit 字段中输入的 IP 地址。在“readip”函数上,我试图获取 lineEdit 的值,但我从未得到我输入的值。我尝试了 ip =str(gui.lineEdit.text()) 和 ip=str(gui.lineEdit.text)。 ip=str(gui.lineEdit.text) 给了我对象的内存槽,而不是 ip 地址。

我正在附加我的应用程序中的代码。请告诉我我做错了什么

这是我的主要应用程序:

import Gui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import PyQt4
import subprocess
import time
import os
import sys
from threading import Thread



class Gui(QDialog,Gui.Ui_mGui):
    def __init__(self,parent=None):
        global ip

        super(Gui,self).__init__(parent)
        self.setupUi(self)

        self.connect(self.instructionButton, SIGNAL("clicked()"), self.showInstructions)
        Gui.connect(self.serviceButton, SIGNAL("clicked()"), backendServiceClass)
        self.checkBox.stateChanged.connect(self.autostartService)


        if self.checkBox.isChecked():

            print "The AutoStartService Button was checked"
            #backendService()

        else:
            print "The AutoStartService Button was not checked"




    def readip(self):
        global ip
        gui=Gui()
        ip=str(gui.lineEdit.text())
        print ip
        time.sleep(1)
        print"test"
        print ip
        time.sleep(20)



    def showInstructions(self):
        QMessageBox.information(self,"Instructions","Enter the IP address of a mobile device you carry with you always.The Application would check whether it can reach that device using your wireless network. If the device is unreachable, it would put the computer to sleep!")

    def autostartService(self):
        if self.checkBox.isChecked():
            autoStartService=1
            TrackAutoStartService = open("AutoStartService", "w+")
            TrackAutoStartService.write(str(autoStartService))
            TrackAutoStartService.close
            print "Autostart Service Checked"
            print autoStartService
        else:
            autoStartService = 0
            TrackAutoStartService = open("AutoStartService", "w+")
            TrackAutoStartService.write(str(autoStartService))
            TrackAutoStartService.close
            print "Autostart Service Unchecked"
            print autoStartService

class backendServiceClass(Thread,Gui):
    def __init__(self,parent=None):
        Thread.__init__(self)
        self.daemon = True
        self.start()

    def run(Gui):
        global loop
        global ip


        Gui.readip()


        print ip

        print ip

        TrackIP = open("TrackIP", "w+")
        TrackIP.write(ip)
        TrackIP.close
        if loop==1:
            loop=0
            #Gui.serviceButton.setText("Start Service")
        else:
            loop=1
            #Gui.serviceButton.setText("Stop Service")

        print("ping -n 1 -w 1000 " + ip)
        down = 0





        while loop==1:
            try:
                response = subprocess.check_output(
                    ['ping', '-n', '1', '-w', '2000', ip],
                    stderr=subprocess.STDOUT,  # get all output
                    universal_newlines=True,  # return string not bytes
                    shell=True,
                    creationflags=subprocess.SW_HIDE
                )
            except subprocess.CalledProcessError:
                response = None

            if (response != None):
                down = 0
                time.sleep(1)
                print ("The host" + ip + " is Alive!")

            else:
                down = down + 1
                time.sleep(1)
                print (down)
                if (down == 10):
                    print ("a total of " + str(down) + "pings has been lost")
                    down = 0
                    time.sleep(10)
                    os.system("shutdown -h")




global loop
loop=0
app=QApplication(sys.argv)
form=Gui()
form.show()




app.exec_()

下面是 Gui.py

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

# Form implementation generated from reading ui file 'Gui.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_mGui(object):
    def setupUi(self, mGui):
        mGui.setObjectName(_fromUtf8("mGui"))
        mGui.resize(246, 308)
        mGui.setMinimumSize(QtCore.QSize(246, 308))
        mGui.setMaximumSize(QtCore.QSize(246, 309))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/image/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        mGui.setWindowIcon(icon)
        self.checkBox = QtGui.QCheckBox(mGui)
        self.checkBox.setGeometry(QtCore.QRect(20, 140, 201, 20))
        f = open("AutoStartService", "r+")
        AutoStartService = int(f.read())
        if AutoStartService == 1:
            self.checkBox.setChecked(True)
        else:
            self.checkBox.setChecked(False)
        self.checkBox.setObjectName(_fromUtf8("checkBox"))
        self.SleeperLabel = QtGui.QLabel(mGui)
        self.SleeperLabel.setGeometry(QtCore.QRect(90, 10, 131, 51))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Harlow Solid Italic"))
        font.setPointSize(28)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.SleeperLabel.setFont(font)
        self.SleeperLabel.setObjectName(_fromUtf8("SleeperLabel"))
        self.SleeperLabel_2 = QtGui.QLabel(mGui)
        self.SleeperLabel_2.setGeometry(QtCore.QRect(10, 10, 71, 61))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Harlow Solid Italic"))
        font.setPointSize(28)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.SleeperLabel_2.setFont(font)
        self.SleeperLabel_2.setText(_fromUtf8(""))
        self.SleeperLabel_2.setPixmap(QtGui.QPixmap(_fromUtf8(":/image/logo64x64.png")))
        self.SleeperLabel_2.setObjectName(_fromUtf8("SleeperLabel_2"))
        self.serviceButton = QtGui.QPushButton(mGui)
        self.serviceButton.setGeometry(QtCore.QRect(10, 260, 101, 31))
        self.serviceButton.setObjectName(_fromUtf8("serviceButton"))
        self.instructionButton = QtGui.QPushButton(mGui)
        self.instructionButton.setGeometry(QtCore.QRect(130, 260, 101, 31))
        self.instructionButton.setObjectName(_fromUtf8("instructionButton"))
        self.label = QtGui.QLabel(mGui)
        self.label.setGeometry(QtCore.QRect(20, 210, 151, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(mGui)
        self.label_2.setGeometry(QtCore.QRect(20, 80, 171, 16))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.checkBox_2 = QtGui.QCheckBox(mGui)
        self.checkBox_2.setGeometry(QtCore.QRect(20, 160, 221, 20))
        self.checkBox_2.setObjectName(_fromUtf8("checkBox_2"))
        self.label_3 = QtGui.QLabel(mGui)
        self.label_3.setGeometry(QtCore.QRect(20, 190, 151, 16))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.lineEdit = QtGui.QLineEdit(mGui)
        self.lineEdit.setGeometry(QtCore.QRect(20, 98, 181, 31))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(mGui)
        QtCore.QMetaObject.connectSlotsByName(mGui)

    def retranslateUi(self, mGui):
        mGui.setWindowTitle(_translate("mGui", "Sleeper V3.0", None))
        self.checkBox.setText(_translate("mGui", "Autostart Service at Application start", None))
        self.SleeperLabel.setText(_translate("mGui", "Sleeper", None))
        self.serviceButton.setText(_translate("mGui", "Start Service", None))
        self.instructionButton.setText(_translate("mGui", "Instructions", None))
        self.label.setText(_translate("mGui", "Currently Tracking the device :", None))
        self.label_2.setText(_translate("mGui", "IP Address of your Mobile Device", None))
        self.checkBox_2.setText(_translate("mGui", "Autostart Application at System Startup", None))
        self.label_3.setText(_translate("mGui", "Service Status :", None))
        f1 = open("TrackIP", "r+")
        IP = str(f1.read())
        if IP != "":
            self.lineEdit.setText(_translate("mGui", IP, None))
        self.lineEdit.setPlaceholderText(_translate("mGui", "Mobile IP", None))

import xz_rc

if __name__ == "__main__":
    import sys



    app = QtGui.QApplication(sys.argv)
    mGui = QtGui.QWidget()
    ui = Ui_mGui()
    ui.setupUi(mGui)
    mGui.show()
    sys.exit(app.exec_())

如果您需要更多信息,请告诉我

【问题讨论】:

  • readip()中,不需要创建一个新的Gui实例。使用selfself.lineEdit.text()

标签: python-2.7 pyqt pyqt4


【解决方案1】:

好吧,老实说,您的代码中存在许多缺陷。你的问题来自于它。

  • global loop

您不必使用全局变量。您可以通过构造函数将它们传递给类并保存为实例变量。

  • Gui.connect(self.serviceButton, SIGNAL("clicked()"), backendServiceClass)

与其在单击时创建和启动对象,不如在 Gui 构造函数中创建它并在单击时启动它。

# Gui init self.service = backendServiceClass(parent=self) ... self.serviceButton.clicked.connect(self.service.start)

  • class backendServiceClass(Thread, Gui):

不要从 Gui 继承。

  • class backendServiceClass(Thread, Gui): ... def run(Gui): .... Gui.readip()

这是你的问题。尽管将self 变量重命名为Gui,它仍然指向您的backendServiceClass 实例。而且,因为你继承自 Gui 类,它有 lineEdit 对象。但是您更改的lineEdit 不一样。

更新:

我稍微修改了你的代码,所以这是一个有效的代码:

gui.py

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

# Form implementation generated from reading ui file 'Gui.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8


    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)


class Ui_mGui(object):
    def setupUi(self, mGui):
        mGui.setObjectName(_fromUtf8("mGui"))
        mGui.resize(246, 308)
        mGui.setMinimumSize(QtCore.QSize(246, 308))
        mGui.setMaximumSize(QtCore.QSize(246, 309))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/image/logo.png")),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        mGui.setWindowIcon(icon)
        self.checkBox = QtGui.QCheckBox(mGui)
        self.checkBox.setGeometry(QtCore.QRect(20, 140, 201, 20))
        self.checkBox.setObjectName(_fromUtf8("checkBox"))
        self.SleeperLabel = QtGui.QLabel(mGui)
        self.SleeperLabel.setGeometry(QtCore.QRect(90, 10, 131, 51))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Harlow Solid Italic"))
        font.setPointSize(28)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.SleeperLabel.setFont(font)
        self.SleeperLabel.setObjectName(_fromUtf8("SleeperLabel"))
        self.SleeperLabel_2 = QtGui.QLabel(mGui)
        self.SleeperLabel_2.setGeometry(QtCore.QRect(10, 10, 71, 61))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Harlow Solid Italic"))
        font.setPointSize(28)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.SleeperLabel_2.setFont(font)
        self.SleeperLabel_2.setText(_fromUtf8(""))
        self.SleeperLabel_2.setPixmap(
            QtGui.QPixmap(_fromUtf8(":/image/logo64x64.png")))
        self.SleeperLabel_2.setObjectName(_fromUtf8("SleeperLabel_2"))
        self.serviceButton = QtGui.QPushButton(mGui)
        self.serviceButton.setGeometry(QtCore.QRect(10, 260, 101, 31))
        self.serviceButton.setObjectName(_fromUtf8("serviceButton"))
        self.instructionButton = QtGui.QPushButton(mGui)
        self.instructionButton.setGeometry(QtCore.QRect(130, 260, 101, 31))
        self.instructionButton.setObjectName(_fromUtf8("instructionButton"))
        self.label = QtGui.QLabel(mGui)
        self.label.setGeometry(QtCore.QRect(20, 210, 151, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(mGui)
        self.label_2.setGeometry(QtCore.QRect(20, 80, 171, 16))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.checkBox_2 = QtGui.QCheckBox(mGui)
        self.checkBox_2.setGeometry(QtCore.QRect(20, 160, 221, 20))
        self.checkBox_2.setObjectName(_fromUtf8("checkBox_2"))
        self.label_3 = QtGui.QLabel(mGui)
        self.label_3.setGeometry(QtCore.QRect(20, 190, 151, 16))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.lineEdit = QtGui.QLineEdit(mGui)
        self.lineEdit.setGeometry(QtCore.QRect(20, 98, 181, 31))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(mGui)
        QtCore.QMetaObject.connectSlotsByName(mGui)

    def retranslateUi(self, mGui):
        mGui.setWindowTitle(_translate("mGui", "Sleeper V3.0", None))
        self.checkBox.setText(
            _translate("mGui", "Autostart Service at Application start", None))
        self.SleeperLabel.setText(_translate("mGui", "Sleeper", None))
        self.serviceButton.setText(_translate("mGui", "Start Service", None))
        self.instructionButton.setText(
            _translate("mGui", "Instructions", None))
        self.label.setText(
            _translate("mGui", "Currently Tracking the device :", None))
        self.label_2.setText(
            _translate("mGui", "IP Address of your Mobile Device", None))
        self.checkBox_2.setText(
            _translate("mGui", "Autostart Application at System Startup",
                       None))
        self.label_3.setText(_translate("mGui", "Service Status :", None))
        self.lineEdit.setPlaceholderText(_translate("mGui", "Mobile IP", None))

主应用

import subprocess
import time
import os
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from Gui import Ui_mGui


class Gui(QDialog, Ui_mGui):
    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        self.setupUi(self)

        f = open("AutoStartService", "r+")
        AutoStartService = int(f.read())
        if AutoStartService == 1:
            self.checkBox.setChecked(True)
        else:
            self.checkBox.setChecked(False)
        f.close()

        f = open("TrackIP", "r+")
        IP = str(f.read())
        if IP != "":
            self.lineEdit.setText(IP)
        f.close()

        self.service = backendServiceClass(parent=self)

        self.connect(self.instructionButton, SIGNAL("clicked()"),
                     self.showInstructions)
        Gui.connect(self.serviceButton, SIGNAL("clicked()"),
                    lambda: self.service.toggle_service(self.lineEdit.text()))
        self.checkBox.stateChanged.connect(self.autostartService)

        if self.checkBox.isChecked():
            print "The AutoStartService Button was checked"
            # backendService()
        else:
            print "The AutoStartService Button was not checked"

    def showInstructions(self):
        QMessageBox.information(self, "Instructions",
                                "Enter the IP address of a mobile device you carry with you always.The Application would check whether it can reach that device using your wireless network. If the device is unreachable, it would put the computer to sleep!")

    def autostartService(self):
        if self.checkBox.isChecked():
            autoStartService = 1
            print "Autostart Service Checked"
        else:
            autoStartService = 0
            print "Autostart Service Unchecked"
        print autoStartService

        TrackAutoStartService = open("AutoStartService", "w+")
        TrackAutoStartService.write(str(autoStartService))
        TrackAutoStartService.close()


class backendServiceClass(QThread):
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.daemon = True
        self.ip = None

    def toggle_service(self, ip):
        if self.isRunning():
            self.terminate()
            self.parent().serviceButton.setText("Start Service")
        else:
            self.parent().serviceButton.setText("Stop Service")
            self.ip = str(ip)
            self.start()

    def run(self):
        TrackIP = open("TrackIP", "w+")
        TrackIP.write(self.ip)
        TrackIP.close()
        print("ping -n 1 -w 1000 " + self.ip)
        down = 0

        while 1:
            try:
                response = subprocess.check_output(
                    ['ping', '-n', '1', '-w', '2000', self.ip],
                    stderr=subprocess.STDOUT,  # get all output
                    universal_newlines=True,  # return string not bytes
                    shell=True,
                    creationflags=subprocess.SW_HIDE
                )
            except subprocess.CalledProcessError:
                response = None

            if (response != None):
                down = 0
                time.sleep(1)
                print ("The host" + self.ip + " is Alive!")

            else:
                down = down + 1
                time.sleep(1)
                print (down)
                if (down == 10):
                    print ("a total of " + str(down) + "pings has been lost")
                    down = 0
                    time.sleep(10)
                    os.system("shutdown -h")


app = QApplication(sys.argv)
form = Gui()
form.show()
app.exec_()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多