我的 python 脚本中导致无限循环的错误是什么

what is the error in my python script that cause an infinite loop

我有一个 python class 创建一个 window 其中包括

EditLine 将在其中获取作为文件夹路径的用户输入。

问题是一旦我 运行 脚本进入无限循环。

代码:

'''
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_())

这里的问题是您在 class 初始化中调用了 checkPath()

checkPath() 读取路径一次,然后开始评估该路径是否有效'forever'。 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()

您还必须从 checkPath(self, checkPath) 中删除 pathOfFile 参数,因为您没有使用它。

因为我们为我们的 checkPath() 函数决定了不同的行为,我们不再需要 while 循环:我们将在每次 event 发生时读取用户输入,评估用户输入,return 用户输入,如果我们喜欢,或者 return 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 False