Python Forum
Multiple.ui windows showing at the same time when I only want to show at a time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple.ui windows showing at the same time when I only want to show at a time
#1
Hey all,

I have the following code below.

I am trying to show take the user through an experiment, where the experiment is split into different windows (window 1, then window 2, then the next window etc).

However, when I run the following code, all the windows are appearing at the same time , despite me using the window.close() function (to close one window once the response has been given).

I would be so grateful for a helping hand as to where I might be going wrong!

import pandas as pd 
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QPixmap
import sys 
import random 

app = QApplication([])

name = []
age = []
gender = []
education = [] 
choiceround1 = []
choiceround2 = []
choiceround3 = []
urnpositionrounds = [] 

window = uic.loadUi("/Users/macbook/Desktop/assignment2file.ui")
window2 = uic.loadUi("/Users/macbook/Desktop/assignment2file2.ui")
window3 = uic.loadUi("/Users/macbook/Desktop/assignment2file3.ui")
window4 = uic.loadUi("/Users/macbook/Desktop/assignment2file4.ui")
window5 = uic.loadUi("/Users/macbook/Desktop/UCL PhD Work/16023114/assignment2file5.ui")
window6 = uic.loadUi("/Users/macbook/Desktop/UCL PhD Work/16023114/assignment2file6.ui")
window7 = uic.loadUi("/Users/macbook/Desktop/UCL PhD Work/16023114/assignment2file7.ui")
window8 = uic.loadUi("/Users/macbook/Desktop/UCL PhD Work/16023114/assignment2file8.ui")
window9 = uic.loadUi("/Users/macbook/Desktop/UCL PhD Work/16023114/assignment2file9.ui")

marbles2random = QPixmap('/Users/macbook/Desktop/2random')
marbles25050 = QPixmap('/Users/macbook/Desktop/25050')
marbles10random = QPixmap('/Users/macbook/Desktop/10random')
marbles105050 = QPixmap('/Users/macbook/Desktop/105050')
marbles100random = QPixmap('/Users/macbook/Desktop/100random')
marbles1005050 = QPixmap('/Users/macbook/Desktop/1005050')

emptydataframe = pd.DataFrame()

j = 0 
while (j < 12):

    window.show()
   
    windows = [window3]
    windows2 = [window4]

    def shownewwindow():
        window2.show()
        window.close()
        
    window.pushButton.clicked.connect(shownewwindow)
    window2.labelerror.hide()

    #randomly selecting order of conditions (2 vs 10 vs 100 marbles)

    selectedwindowindex = random.sample(range(len(windows)),3)
    selectedwindow = windows[selectedwindowindex[0]]
    selectedwindow2 = windows[selectedwindowindex[1]]
    selectedwindow3 = windows[selectedwindowindex[2]]
    selectedwindows = [selectedwindow,selectedwindow2,selectedwindow3]
    selectedsecondwindow = windows2[selectedwindowindex[0]]
    selectedsecondwindow2 = windows2[selectedwindowindex[1]]
    selectedsecondwindow3 = windows2[selectedwindowindex[2]]
    selectedsecondwindows = [selectedsecondwindow,selectedsecondwindow2,selectedsecondwindow3]

    #randomly assigning random vs fixed jar of marbles to left and right urn

    allmarblesrandom = [marbles2random,marbles10random,marbles100random]
    allmarbles5050 = [marbles25050,marbles105050,marbles1005050]
    allmarblesrandomone = allmarblesrandom[selectedwindowindex[0]]
    allmarblesrandomtwo = allmarblesrandom[selectedwindowindex[1]]
    allmarblesrandomthree = allmarblesrandom[selectedwindowindex[2]]
    randommarbles = [allmarblesrandomone,allmarblesrandomtwo,allmarblesrandomthree]
    allmarbles5050one = allmarbles5050[selectedwindowindex[0]]
    allmarbles5050two = allmarbles5050[selectedwindowindex[1]]
    allmarbles5050three = allmarbles5050[selectedwindowindex[2]]
    marbles5050 = [allmarbles5050one,allmarbles5050two,allmarbles5050three]

    #ensuring that all response boxes have been filled in 

    def checkText():
        if((window2.Name.text()== "") or (window2.Gender.text()== "") or (window2.Age.text()== "") or (window2.Education.text()== "")):
            window2.labelerror.setText("One of the boxes has not yet been filled in!")
            window2.labelerror.show()
        else:
            username = window2.Name.text()
            name.append(username)
            print(name)
            userage = window2.Age.text()
            age.append(userage)
            print(age)
            usergender = window2.Gender.text()
            gender.append(usergender)
            print(gender)
            usereducation = window2.Education.text()
            education.append(usereducation)
            print(education)
            window2.labelerror.hide()
            window2.close()
    
    window2.submitbutton.clicked.connect(checkText)

    #run experiment based on order of randomly-selected conditions (number of marbles in jar)

    for i in range(0,len(selectedwindows)):
        selectedwindow = selectedwindows[i]
        selectedsecondwindow = selectedsecondwindows[i]
        selectedwindow.show()
        allmarblesrandomone = randommarbles[i]
        allmarbles5050one = marbles5050[i]
        marblechoices = [allmarblesrandomone,allmarbles5050one]
        rightsidechoice = random.choice(marblechoices)
        marblechoices.remove(rightsidechoice)
        leftsidechoice = random.choice(marblechoices)
    
        def shownewwindow():
          if 'random' in str(rightsidechoice):
            urnposition = 0
            urnpositionrounds.append(urnposition)
            selectedsecondwindow.rightlabel.setPixmap(rightsidechoice)
            selectedsecondwindow.leftlabel.setPixmap(leftsidechoice)
            selectedsecondwindow.show()
            selectedwindow.close()
          else:
            urnposition = 1 
            urnpositionrounds.append(urnposition)
            selectedsecondwindow.rightlabel.setPixmap(leftsidechoice)
            selectedsecondwindow.leftlabel.setPixmap(rightsidechoice)
            selectedsecondwindow.show()
            selectedwindow.close()
        
        selectedwindow3.pushButton.clicked.connect(shownewwindow)
        
        def shownewwindow2():
            answer = 0
            emptydataframe.iloc[0,i] = answer
            print(emptydataframe)
            selectedsecondwindow.close()
                
        def shownewwindow3():
            answer = 1
            emptydataframe.iloc[0,i] = answer
            print(emptydataframe)
            selectedsecondwindow.close()
        
        selectedsecondwindow.Left.clicked.connect(shownewwindow2)
        selectedsecondwindow.Right.clicked.connect(shownewwindow3)

    #ending screen

    window9.show()
           
    def shownewwindow4():
        window9.close()
    
    window9.pushButton.clicked.connect(shownewwindow4)

    j = j + 1

    app.exec_()
Reply
#2
Please take a look at the free Project Jupyter I think this is exactly what you're looking for.
Run the demo in your browser, short and sweet.

You can break your code into the component windows, and wrap your presentation around each component, only executing when you want them to.

I have done several public presentations using this method, and it's great.
Reply
#3
(Dec-19-2022, 12:13 PM)Larz60+ Wrote: Please take a look at the free Project Jupyter I think this is exactly what you're looking for.
Run the demo in your browser, short and sweet.

You can break your code into the component windows, and wrap your presentation around each component, only executing when you want them to.

I have done several public presentations using this method, and it's great.

I'm very sorry but this hasn't really helped me solve my issue :)
Reply
#4
You could open Window 2 on closing Window 1

Window1

from PyQt5.QtWidgets import (QMainWindow, QApplication, QVBoxLayout, 
                             QWidget)
import window_2

class mainWin(QMainWindow):
    def __init__(self, parent = None):
        super(mainWin, self).__init__(parent)
        self.setupUI()
        
    def setupUI(self):
        self.setWindowTitle("Window 1")
        self.setGeometry(0, 0, 800, 600)
        central_widget = QWidget()
        vbox = QVBoxLayout()
        central_widget.setLayout(vbox)
        self.setCentralWidget(central_widget)
        self.show()

        
    def closeEvent(self, event):
        print("closing 1")
        self.w_2 = window_2.mainWin()
        self.w_2.show()


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = mainWin()

    app.exec_()
Window2

from PyQt5.QtWidgets import (QMainWindow, QApplication, QVBoxLayout, 
                             QWidget)

class mainWin(QMainWindow):
    def __init__(self, parent = None):
        super(mainWin, self).__init__(parent)
        self.setupUI()
        
    def setupUI(self):
        self.setGeometry(0, 0, 800, 600)
        central_widget = QWidget()
        vbox = QVBoxLayout()
        central_widget.setLayout(vbox)
        self.setCentralWidget(central_widget)
        self.setWindowTitle("Window 2")
        self.show()
        
    def closeEvent(self, event):
        print("closing 2")


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = mainWin()

    app.exec_()
Reply
#5
I don't think you understand how Qt works. It, and most gui toolkits work the same way, is based on an event/action paradigm. You create a bunch of controls, define a bunch of actions, and then bind your actions to events that are raised when the user interacts with the controls. An event manager looks up the action to perform when the event is raised, and executes your action code. In Qt, the events are called "signals", the actions are called "slots", and the event manager is exec() (or exec_())..

Your while loop doesn't make any sense in a gui program. The sequence of code execution is controlled by the user, not the order of statements in your program. Instead of a loop you need to write a function or method that is called when the user closes (or tries to close) one of the windows. This function checks if the window can be closed and decides which window to open next.

Below is a simple example. It creates a bunch of windows that have a button. The button clicked signal (action) is connected to a method (action) that closes the current window and draws the next window. I randomly have the windows refuse when asked to close. In a real program the window would refuse to close if it was an uncompleted form.
from PySide6.QtWidgets import QWidget, QApplication, QPushButton, QVBoxLayout, QMessageBox
import random

class Window(QWidget):
    def __init__(self, id, callback):
        super().__init__()
        self.button = QPushButton(text=f'Button {id}', parent=self)
        self.button.clicked.connect(callback)
        layout = QVBoxLayout(self)
        layout.addWidget(self.button)

    def close(self):
        if random.choice((False, False, True)):
            # I cannot be closed at this time.
            raise RuntimeError("I'm busy.")
        super().close()


class WindowManager:
    """A thing that decides which window to draw next"""
    def __init__(self):
        self.windows = []
        self.index = 0

    def add(self, window):
        if not self.windows:
            window.show()
        self.windows.append(window)

    def next(self):
        """This is where you would put your logic that decides
        which window to draw next.  Here I just display windows
        sequentially.
        """
        window = self.windows[self.index]
        try:
            window.close()
            self.index += 1
            if self.index < len(self.windows):
                self.windows[self.index].show()
        except RuntimeError as msg:
            QMessageBox.information(QMessageBox(window), "Sorry", msg.args[0])


def main():
    app = QApplication()
    manager = WindowManager()
    for i in range(1, 10):
        manager.add(Window(i, manager.next))
    app.exec()


main()
I agree with Larz60+ in thinking that a Jupyter notebook might be a great choice for doing something like this. A Jupyter notebook has a kind of sequential execution built in. Changes made to the first page can affect what happens in the second page. Maybe more importantly, the presentation is also sequential in nature, like paging through a really impressive lab notebook.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Date Time Series Help...Please spra8560 2 382 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Python date format changes to date & time 1418 4 628 Jan-20-2024, 04:45 AM
Last Post: 1418
  time difference bettwenn logs enkliy 14 1,014 Nov-21-2023, 04:51 PM
Last Post: rob101
Question Need Help with Vehicle Routing Problem with Time Windows (VRPTW) in Python kasper321421312 1 582 Nov-10-2023, 08:19 PM
Last Post: snippsat
  How do I stream and record at the same time with arducam? traderjoe 0 474 Oct-23-2023, 12:01 AM
Last Post: traderjoe
  i tried to install python for the first time today and pretty certain im being remote brianlj 2 558 Oct-03-2023, 11:15 AM
Last Post: snippsat
  [Python 2.7] Why can't I press [ESC] a fourth time? Ashwood 3 670 Aug-27-2023, 02:01 PM
Last Post: deanhystad
  Hard time trying to figure out the difference between two strings carecavoador 2 686 Aug-16-2023, 04:53 PM
Last Post: carecavoador
  return next item each time a function is executed User3000 19 2,316 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,060 Jul-23-2023, 08:32 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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