我有一个程序,它将用户输入存储到变量中,检查它是否是IP地址并从那里执行功能。
我想添加一个窗口使它看起来更好,并且我很难从窗口中存储变量。
我希望能够- -收集用户输入并将其存储在变量中 -在函数中使用该变量来检查它是否与IP地址匹配,如果匹配,则执行if语句。
这是我一直在玩的教程中的示例代码-
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'IP / Domain'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.getInteger()
self.getText()
self.getDouble()
self.getChoice()
self.show()
def getText(self):
userInput, okPressed = QInputDialog.getText(self, "Get text", "Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(userInput)
def ipFormatChk(userInput): #input
pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\." \
r"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if re.match(pattern, userInput)
#do something
return
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
答案 0 :(得分:0)
尝试一下:
import sys
import re
from PyQt5.QtWidgets import (QApplication, QWidget, QInputDialog, QLineEdit,
QLabel, QVBoxLayout, QPushButton)
from PyQt5.QtGui import QIcon
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'IP / Domain'
self.left = 50
self.top = 50
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.label = QLabel()
self.label.setStyleSheet("color: green; font: 16px;")
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(QPushButton("Enter IP-address", clicked=self.getText))
self.setLayout(layout)
#self.getInteger()
#self.getText()
#self.getDouble()
#self.getChoice()
self.show()
def getText(self):
userInput, okPressed = QInputDialog.getText(
self,
"Input IP-address",
"Your IP-address:",
QLineEdit.Normal, "")
if okPressed: # and userInput != '':
#print(userInput)
if userInput.strip():
self.ipFormatChk(userInput)
else:
self.label.setStyleSheet("color: red; font: 24px;")
self.label.setText("Input line is empty, enter IP-address")
else:
self.label.setText("")
def ipFormatChk(self, userInput):
pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\." \
r"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if re.match(pattern, userInput):
additionalText = "This is IP-address"
self.label.setStyleSheet("color: lightgreen; font: 24px;")
else:
additionalText = "This is NOT an IP-address"
self.label.setStyleSheet("color: red; font: 24px;")
self.label.setText("{} <- {}".format(userInput, additionalText))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())