2017-02-28 8 views
0

これは単純な/愚かなエラーであるか、すでに回答があった場合、私はお詫びします。私はプログラミングに非常に慣れていて、自分自身を教育しています。これは私の最初の質問stackoverflowですので、もし私があなたの詳細情報が必要か、私の質問が明確ではないことを教えてください。pyqt4 lineの空白値が返されます

私のコードは、私の行編集フィールドに入力した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_()) 

あなたはさらに情報が必要な場合は私に知らせてください

+0

PY、新しい 'Gui'インスタンスを作成する必要はありません。 'self'を使う:' self.lineEdit.text() ' – Crispin

答えて

0

まあ、正直言って、あなたのコードには多くの欠陥があります。あなたの問題はそれに由来します。

  • global loop

あなたはグローバル変数を使用する必要はありません。コンストラクタを介してクラスに渡し、インスタンス変数として保存することができます。

  • Gui.connect(self.serviceButton, SIGNAL("clicked()"), backendServiceClass)
  • GUIではなくコンストラクタでそれを作成し、クリック時に、それを起動し、より良いあなたをクリックして上のオブジェクトを作成し、開始の

    • class backendServiceClass(Thread, Gui):

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

      は、GUIから継承しません。

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

      これはあなたの問題です。 self変数の名前をGuiに変更したにもかかわらず、依然としてbackendServiceClassインスタンスを指しています。そしてGuiクラスから継承したので、それにはlineEditオブジェクトがあります。しかし、あなたが変更するのは同じlineEditではありません。

      UPDATE:

      桂:私はあなたのコードを少し変更し

      ので、ここで作業コードです。`readip()`で

      # -*- 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_() 
      
    関連する問題