卡在一个回路上!

2024-06-25 23:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个应用程序,该应用程序将用于将图像上载到指定的服务器。我已经在Qt设计器中创建了GUI,一切都很好,我只是停留在一些我知道很简单的东西上。我好像不能把我的头绕过去。在

这个想法是让脚本遍历并查看有多少文本字段与图像的路径一起归档-从中获取每个路径并按顺序将每个路径上载到服务器。我可以让它只使用一个盒子就可以了,但是当我试图为这个过程创建一个循环时,它就崩溃了。我基本上需要返回'fullname'和每个不同的路径。这只是一个窃听,但你明白了。。在

这个概念似乎很简单,我已经尽可能多的重写了这篇文章,我可以找到并思考。任何帮助都会很棒的。我应该用列表来代替吗?在

        # count how many images there are going to be
    if not self.imgOnePathLabel.text().isEmpty():
        totalImages = 1
        # gets the path from IMAGE 1 box
        image1 = self.imgOnePathLabel.text()
        fullname = '%s' % image1
    if not self.imgTwoPathLabel.text().isEmpty():
        totalImages = 2
        image2 = self.img2PathLabel.text()
        fullname = '%s' % image2
    if not self.imgThreePathLabel.text().isEmpty():
        totalImages = 3
        imageThreePath = self.imgThreePathLabel.text()
        fullname = '%s' % imageThreePath
    try:
        for x in range(1,totalImages,1):
            # split end file from the file path
            name = os.path.split(fullname)[1]
            f = open(fullname, "rb")
            # store our selected file
            ftp.storbinary('STOR ' + name, f)
            msg = "Sent <font color=green>" + name + "</font>"
            self.logBrowser.append(msg)
            f.close()

    finally:
        msg = "<font color=green>" "Ok" "</font>"
        self.logBrowser.append(msg)

Tags: pathtextname图像self路径应用程序if
3条回答

除了范围需要为+1才能达到#3的问题(参见Vincent R的备注)

(其中一个)问题是fullname变量被每个新的非空标签大小写覆盖。在

很难对代码进行评论以修复它,也就是说,我想建议并重新组织一下。例如,通过引入一个函数来提取给定图像的名称/路径(给定UI对象);这将避免一些重复。这样一个函数,或者它的调用者,会将每个新的全名添加到它的一个列表中,然后upload循环就可以使用它。在

参见Tendayi Mawushe的解决方案,它尊重原始结构,但按照建议引入了一个列表。顺便说一句,这个列表可以作为循环的基础进行迭代,而不是依赖range()函数,这更像python(这就不需要解决范围中缺少#3的问题)。在Python中,这些数值范围驱动的循环虽然有时很方便,但它们常常是重新设计的邀请。在

原始代码的另一个问题是,如果标签1和3不是空的,但是标签2是空的,totalImages将被设置为3,即使您只有两个路径。在

另外,这段代码中的一个错误(“2”对“2”):

if not self.imgTwoPathLabel.text().isEmpty():
    image2 = self.img2PathLabel.text()

我相信您不需要字符串替换'%s' % image。在

您可以这样压缩代码(并解决问题):

^{pr2}$

您的问题是,您分配给变量fullname三次,每次都重写它。所以当你进入for循环时,只有最后一个文件名是可用的,如果最后一个字段已经设置,否则你什么都得不到。你说你需要一个全名列表而不是一个变量是正确的。您需要以下内容:

    fullnames = []
    imageLabels = [self.imgOnePathLabel, self.imgTwoPathLabel,
            self.imgThreePathLabel]
    for imageLabel in imageLabels:
        if imageLabel.text():
            image = self.imgOnePathLabel.text()
            fullnames.append('%s' % image)
    try:
        for fullname in fullnames:
            # split end file from the file path
            name = os.path.split(fullname)[1]
            f = open(fullname, "rb")
            # store our selected file
            ftp.storbinary('STOR ' + name, f)
            msg = "Sent <font color=green>" + name + "</font>"
            self.logBrowser.append(msg)
            f.close()
    finally:
        msg = "<font color=green>" "Ok" "</font>"
        self.logBrowser.append(msg)

相关问题 更多 >