嗨,为了学习,我创建了这个基本程序来ping一个在Windows上运行的主机。
请批评并纠正。
我最关心的是disable_button函数。
我确保“line_edit_hostname”中的输入仅在用户输入的字符串中包含1个字符并且具有“。”时才有效。在文中。
我这样做的原因是因为当我输入一个没有'。'的字符串时ping崩溃了。
然而,有一种解决方法,一旦用户输入一个包含多个字符和'。'的字符串,他们就可以点击退格按钮然后继续该程序。
我打算在disable_button函数上放置一个while循环,因此它可以关注文本验证,但这似乎会使程序崩溃。
阅读之后,我认为它与在函数disable_button函数中没有使用的线程有关。我尝试了标准的线程模块并没有取得任何进展,因此我发现自己在这里寻求帮助:)
如果有人可以通过正确的线程纠正它,或者甚至可以重新编写一个更好的版本,我可以从中学到很棒。
感谢您的时间。
#!python3
import subprocess
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# import threading
""" An example of a GUI Program that can ping a host """
# Class for the Application
class NetworkCheck(QDialog):
def __init__(self):
QDialog.__init__(self)
# make it a vertical box layout in the main form
layout = QVBoxLayout()
# Widgets
# When we add self in front of a Variable they become instance wide
self.label_hostname = QLabel("Please enter a Hostname")
self.line_edit_hostname = QLineEdit()
self.label_ip = QLabel("Host IP Address:")
self.line_edit_ip_address = QLineEdit()
self.btn_ok = QPushButton("Ok")
self.btn_clear = QPushButton("Clear")
self.btn_exit = QPushButton("Exit")
# Always add PlaceHolder Text before adding
# The Widget to the layout
self.line_edit_hostname.setPlaceholderText("example.com")
self.line_edit_hostname.setAlignment(Qt.AlignHCenter)
# calls the text_input function we defined to control the input of text to
# make sure it has a "." so the program doesn't crash...
self.line_edit_hostname.setText("")
# When results show in the IP Address and Set it as a Read Only Field..
self.line_edit_ip_address.setAlignment(Qt.AlignHCenter)
self.line_edit_ip_address.setReadOnly(True)
# Align the Labels in the Center of the Window'
self.label_hostname.setAlignment(Qt.AlignHCenter)
self.label_ip.setAlignment(Qt.AlignHCenter)
# Now we need to add the above Widgets to the Form
layout.addWidget(self.label_hostname)
layout.addWidget(self.line_edit_hostname)
layout.addWidget(self.label_ip)
layout.addWidget(self.line_edit_ip_address)
layout.addWidget(self.btn_ok)
layout.addWidget(self.btn_clear)
layout.addWidget(self.btn_exit)
# Now we need to Save the Layout
self.setLayout(layout)
# Change the Main Window Title Name
self.setWindowTitle("Check Host")
# Removes the Focus from QLineEdit()
# This means that the text will always display
# in the QLineEdit field
self.setFocus()
# Stop the Window from being Stretched
# Sets the Width to 250 by 200 Height
self.setFixedSize(250, 200)
# Exit button to close the Main window
self.btn_exit.clicked.connect(self.close)
# Clear Button will clear the line edit fields and disable the Ok button
self.btn_clear.clicked.connect(self.clear_fields)
# Ok button to perform the function...
# disables the button by default..
self.btn_ok.setEnabled(False)
# if Text is entered in the hostname field it calls the disable_button function
# and a "." is also entered in the line_edit field..
self.line_edit_hostname.textChanged.connect(self.disable_button)
def clear_fields(self):
"""Clear the Line Edit Boxes.. and Disables the Ok push button"""
self.line_edit_hostname.setText("")
self.line_edit_ip_address.setText("")
self.btn_ok.setEnabled(False)
def get_ip(self):
try:
# defines the hostname variable to use in the command
hostName = self.line_edit_hostname.displayText()
ping = subprocess.Popen(
["ping", "-n", "1", hostName],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# output of the above command
ping_output, error = ping.communicate()
# get rid of the bytes output...
ping_output = ping_output.decode("utf-8")
# Clean the output to get the IP only...
ip_start = ping_output.index("[") + 1
ip_end = ping_output.index("]")
# get only the ip address..
# global ip_output
ip_output = ping_output[ip_start:ip_end]
# displays the ip address in the line_editip_address field.
self.line_edit_ip_address.setText(ip_output)
except Exception:
# Dialog Box: adds the Title and the Massage...
QMessageBox.warning(self, "Warning", "The Ping Lookup Failed...")
# Terminates the Application...
sys.exit()
# return
# enables the button get results once text has been entered in the line edit field hostname
# and a "." is also entered in the line_edit field..
def disable_button(self):
# while True:
if len(self.line_edit_hostname.text()) > 0 and "." in str(self.line_edit_hostname.text()):
# if the text is greater then 1 char it enables the button
self.btn_ok.setDisabled(False)
# connect to the "OK" button we crated the in the UI and calls the get_ip function
self.btn_ok.clicked.connect(self.get_ip)
# break
# Calling the Application Class
if __name__ == "__main__":
app = QApplication(sys.argv)
window = NetworkCheck()
# enable threading on the get_ip function from the Window class that holds the application.
# t1 = threading.Thread(target=window.get_ip)
# t1.start()
# t1.join()
window.show()
app.exec_()