Python Forum
Huge code problems (buttons(PyQt5),PyQt5 Threads, Windows etc)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Huge code problems (buttons(PyQt5),PyQt5 Threads, Windows etc)
#1
Button reacts like it's pressed... but window's not opened...

New window (with that button) won't open after function (in a Thread Class)...

See more about that down below:

I have a function eBaySearch in the Thread class, which needs to be called when the button is clicked. The thing is that I want to run that function, scrape some information while there is a window on the screen saying (for example) "Your search is in progress...". When the function ends, that window ("Your search is in progress...") needs to close and one new window should be opened. What's the problem ? Well I have a lot of problems in here, code is a mess because I am 15 y.o beginner who worked more in Cpp than in any other language but ok.

First, I can't use threads, probably I don't understand them the right way, so if you can somehow fix this to do what I said (or somewhere near that), it would be really, really good. I don't have much time and I am struggling for some days.

Second, when function ends, the "Your search is in progress..." window closes, but then application stops, doesn't show anything more, doesn't react...

Also, third, I had a problem that it won't open new window, it presses the button that is on that window that should be loaded, and then crashes the application.

What a mess, right ?

Also, I tried creating object without "self" in a class, I tried opening new window in various different places, with and without "self", I am now currently using "bool" to check has search ended but for some reason that doesn't work too.... It worked before like when it sets isEBAYFinished to false, it would print the message in that if statement and even close the window, but won't open the new one.

Well, here's my code that can probably help you out (sorry, I know, it's a mess, but please I don't have much time, so if it's solvable and you can solve it please help me out):
class Window_FinishedNotification_EBAY(QWidget):
    def __init__(self, parent=None):
        super(Window_FinishedNotification_EBAY, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        buttonNext = QPushButton(self)
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        label1.setText("Your search has been finished! Press Next to continue")
        label1.setAlignment(Qt.AlignHCenter)
        buttonNext.setText("Next")
        self.layout.addWidget(label1, 0, 0, 1, 4)
        self.layout.addWidget(buttonNext,1,4,1,1)

        buttonNext.clicked.connect(self.buttonNext_clicked())
        self.setLayout(self.layout)
        self.show()

    def thisButton_сlicked(self):
        print("Jel ovo nesto ?")
        pass

class Window_FinishedNotification_EBAY2(QWidget):
    def __init__(self, parent=None):
        super(Window_FinishedNotification_EBAY2, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        label1.setText("Search in progress...")
        label1.setAlignment(Qt.AlignHCenter)

        self.layout.addWidget(label1, 0, 0, 1, 4)

        #buttonNext.clicked.connect(self.buttonNext_clicked())
        self.setLayout(self.layout)
        self.show()

class Window_eBay_Search(QDialog):
    def __init__(self, parent=None):
        super(Window_eBay_Search, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        lineEdit = QLineEdit(self)
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        buttonNext = QPushButton(self)
        #label2 = QLabel(self)
        label1.setText("Input an article:")
        buttonNext.setText("Next")
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        #label2.setFont(newfont)
        #label2.setStyleSheet("color: red")
        self.layout.addWidget(label1,0,0,1,4)
        self.layout.addWidget(lineEdit,0,4,1,50)
        self.layout.addWidget(buttonNext,0,60,1,1)
        self.layout.addWidget(QLabel(""),4,0,0,50)
        buttonNext.clicked.connect(lambda: self.buttonNext_clicked(self.layout, lineEdit.text()))
        self.setLayout(self.layout)
        self.show()

    def buttonNext_clicked(self, layoutPassed, search2):
        if search2 != "":
            search = search2
            global toSearch
            toSearch = search2
            self.get_thread = InProgressThread()
            #self.get_thread.finished.connect(self.done)
            self.get_thread.start()
            self.window_FinishedNotification_EBAY2 = Window_FinishedNotification_EBAY2()
            global isEBAYFinished
            isEBAYFinished = False
            self.window_FinishedNotification_EBAY2.show()
            self.close()
            if isEBAYFinished == True:
                self.window_FinishedNotification_EBAY2.close()
                print("YES")

        else:
            label2 = QLabel(self)
            label2.setFont(QtGui.QFont("Arial", 10, QtGui.QFont.Bold))
            label2.setStyleSheet("color: red")
            label2.setText("You must enter something")
            layoutPassed.addWidget(label2,4,0,1,4)


    def threadDone(self):
        QMessageBox.warning(self,"DONE :D") # Idk what's this I swear


class InProgressThread(QThread):
    add_post = pyqtSignal(str)
    def __init__(self, parent=None):
        super(InProgressThread,self).__init__(parent)

    def eBaySearch(self):
        global toSearch
        search = toSearch
        print("STARTEDDDDD")
        print("SEARCH: " + toSearch)
        file = open("OutputEBAY", "w")
        baseLink = "https://www.ebay.com/sch/i.html?_from=R40&_nkw="
        # startLink = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=Gtx1050&_sacat=0"
        startLink = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw="
        for i in search:
            if i == " ":
                startLink += "+"
                baseLink += "+"
            else:
                startLink += i
                baseLink += i

        startLink += "&_sacat=0"
        baseLink += "&_sacat=0&_pgn="

        counterDict = {}
        maxDict = {}
        compressedDict = {}
        lastSum = 0
        averagePerPage = []
        totalAverage = 0.0
        for x in range(1, 150):

            counter = 0
            sum = 0.0
            if x == 1:
                generatedLink = startLink
            else:
                generatedLink = baseLink + str(x)

            page = requests.get(generatedLink)
            contents = page.text
            soup = BeautifulSoup(contents, "html.parser")
            mainContentPrice = soup.find_all('span', class_="s-item__price")
            mainContentPlaces = soup.find_all('span', class_=["s-item__location", "s-item__itemLocation"])
            print(generatedLink)
            for i, j in zip(mainContentPrice, mainContentPlaces):
                file.write("UNSLICED:" + str(i.text) + "\n")
                indexT = (i.text).find("t")
                indexComma = (i.text).find(",")

                if indexT != -1:  # There is 't' which represent existence 'to'
                    firstPriceCut = (i.text)[indexT + 3:]
                    indexComma = firstPriceCut.find(",")  # We need to check if there is comma in
                    if indexComma != -1:  # There is comma, which means the price is over $999
                        beforeComma = float(firstPriceCut[1:indexComma]) * 1000
                        afterComma = float(firstPriceCut[indexComma + 1:])
                        price = beforeComma + afterComma

                    else:  # There is no comma, which means the price is less than $1000
                        price = float(firstPriceCut[1:])


                else:  # There is no 't', so there is only one price

                    if indexComma != -1:  # There is comma, which means the price is over $999
                        beforeComma = float((i.text)[1:indexComma]) * 1000
                        afterComma = float((i.text)[indexComma + 1:])
                        price = beforeComma + afterComma

                    else:  # There is no comma, which means the price is less than $1000
                        price = float((i.text)[1:])

                file.write(str(counter) + "SLICED: " + str(price) + "\n")
                sum += price
                counter += 1
                # Adding places and prices to dictionary
                for x in mainContentPlaces:
                    if x.text in compressedDict:
                        compressedDict[x.text] += price
                        counterDict[x.text] += 1

                        if maxDict[x.text] < price:
                            maxDict[x.text] = price

                    else:
                        compressedDict[x.text] = 1
                        counterDict[x.text] = 1
                        maxDict[x.text] = -1

            if sum == lastSum:
                print("SUMAAAA")
                print("LASTSUM:", lastSum)
                break

            if counter > 0:
                averagePerPage.append(sum / counter)
                # totalAverage += sum/counter
                file.write("TOTAL AVERAGE: " + str(totalAverage) + "\n")
                print("SUMA:", sum)
                print("LASTSUM:", lastSum)

            else:
                print("KRAJ2")
                break

            lastSum = sum

        isEBAYFinished = True
        if len(averagePerPage) != 0:
            maxElem = max(i for i in averagePerPage)

            averagePerPage.remove(maxElem)

            for i in averagePerPage:
                totalAverage += i

            print("TOTAL AVERAGE: ${0:.2f}".format(totalAverage / len(averagePerPage)))

            file.write("${0:.2f}".format(totalAverage / len(averagePerPage)))

        else:
            print("Invalid search!")
        isEBAYFinished = True
        window_finishednotification_ebay = Window_FinishedNotification_EBAY()
        window_finishednotification_ebay.show()

        file.close()

    def run(self):
        print("It's here, function's going to be started")
        self.eBaySearch()
        self.add_post.emit("EMITTED")
        print("DONE")
        print("THIS") # I swear I don't understand this "self.add_post.emit("EMITTED" line, I just tried to copy it from the internet but it's impossible to make it work.
(crossposted from StackOverflow)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PyQt5 Relative Layout Unkovic 1 580 Nov-10-2023, 01:52 PM
Last Post: Axel_Erfurt
  How can I run an interface I made using PyQt5 and a Map program I made using Tkinter bki 6 1,047 Nov-09-2023, 11:12 PM
Last Post: bki
  [PyQt] PyQt5 window closing when trying to display a graph bianca 4 1,623 Aug-12-2023, 03:25 PM
Last Post: bianca
Bug [PyQt] PyQt5 _translate not passing argument Lahearle 2 754 Jul-23-2023, 11:05 AM
Last Post: Axel_Erfurt
  [PyQt] PyQt5 drawing on scrollable area HeinKurz 3 1,259 Mar-28-2023, 12:58 PM
Last Post: Axel_Erfurt
  [PyQt] PyQt5 QTableView SQLite : edit cell HeinKurz 2 2,288 Mar-27-2023, 10:41 AM
Last Post: HeinKurz
  help needed running a simple function in pyqt5 diodes 27 8,169 Jan-24-2023, 12:19 PM
Last Post: GetOnData
  [PyQt] PyQt5 graphics question HeinKurz 5 1,406 Jan-17-2023, 07:22 PM
Last Post: deanhystad
  [PyQt] self.pos().x() and self.pos().x() always return -3,-30 on PyQT5 DrakeSoft 3 1,457 Jan-15-2023, 09:28 AM
Last Post: DrakeSoft
  PyQt5, QtSql: connection to database does not work gradlon93 4 1,606 Jan-12-2023, 05:26 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020