我有一个python类,它创建一个窗口,其中包括
其中,EditLine将获得作为文件夹路径的userInput。
问题是,一旦我运行脚本,它就进入无限循环。
代码:
'''
1- import the libraries from the converted file
2- import the converted file
'''
from PyQt5 import QtCore, QtGui, QtWidgets
import pathmsgbox
import os
import pathlib
class path_window(pathmsgbox.Ui_PathMSGbox):
def __init__(self,windowObject ):
self.windowObject = windowObject
self.setupUi(windowObject)
self.checkPath(self.pathEditLine.text())
self.windowObject.show()
def checkPath(self, pathOfFile):
folder = self.pathEditLine.text()
while os.path.exists(folder) != True:
print("the specified path not exist")
folder = self.pathEditLine.text()
return folder
'''
get the userInput from the EditLine
'''
'''
def getText(self):
inputUser = self.pathEditLine.text()
print(inputUser)
'''
'''
function that exit from the system after clicking "cancel"
'''
def exit():
sys.exit()
'''
define the methods to run only if this is the main module deing run
the name take __main__ string only if its the main running script and not imported
nor being a child process
'''
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
PathMSGbox = QtWidgets.QWidget()
pathUi = path_window(PathMSGbox)
pathUi.pathCancelBtn.clicked.connect(exit)
sys.exit(app.exec_())发布于 2018-03-17 16:44:20
这里的问题是在类初始化中调用checkPath()。
checkPath()只读取一次路径,然后开始评估该路径是否“永久”有效。这个while循环运行甚至可能会阻止软件能够有效地从self.pathEditLine中读取文本。
通常,最好将每个函数连接到一个事件:
要执行这些操作,您必须将其中一个事件连接到函数:
按钮事件:
self.btnMyNewButton.clicked.connect(checkPath)文本更改事件:
self.pathEditLine.textChanged.connect(checkPath)输入按钮事件:
self.pathEditLine.returnPressed.connect(checkPath)这意味着您必须用在初始化过程中调用checkPath()函数的行替换前面的一行:
def __init__(self,windowObject ):
self.windowObject = windowObject
self.setupUi(windowObject)
self.pathEditLine.textChanged.connect(checkPath)
self.windowObject.show()您还必须将pathOfFile参数从checkPath(self, checkPath)中删除,因为您没有使用它。
由于我们决定了checkPath()函数的不同行为,我们不再需要一个while循环:我们将在每次event发生时读取用户输入,评估用户输入,如果我们喜欢返回用户输入,或者返回False (如果我们不喜欢):
def checkPath(self):
folder = str(self.pathEditLine.text())
if os.path.exists(folder):
print '%s is a valid folder' % folder
return folder
else:
print '%s is NOT a valid folder' % folder
return Falsehttps://stackoverflow.com/questions/49327154
复制相似问题