I'm Currently making a TextBased game with pyqt5 and I'm using the designer to make the Windows because it was easier, everything was fine until I tried to find out how to Destroy a single Child window I found some Answers but it didn't Fit my Situation (or I'm just bad at this).
Note: I'm using the Designer to Make the UI
Issue: Couldn't Find an Answer to My Problem Which is Destroying a Child Window (HuntTab) when Hp is lesser than 1
import random
from PyQt5 import QtCore, QtGui, QtWidgets
level = 1
job = "NONE"
df = random.randrange(1, 6, 1)
hpMax = random.randrange(95, 120, 1)
hp = hpMax
exp = 0
expMax = 100
attackMax = random.randrange(4, 7, 1)
attackMin = random.randrange(1, 4, 1)
enemyLevel = random.randrange(1, 4, 1)
enemyHp = enemyLevel * 20 + 20
enemyAttackMax = random.randrange(2, 4, 1) * enemyLevel
enemyAttackMin = random.randrange(1, 3, 1) * enemyLevel
luck = 10
looks = 120
class UiMainWindow(object):
UI = f"<html><head/><body><p>Level: {level}</p><p>Job: {job}</p><p>Health: {hp}</p><p>Attack: {attackMin} - {attackMax}</p><p>Defense: {df}</p><p>Luck: {luck}</p><p>Looks: {looks}</p><p><br/></p></body></html>"
def __init__(self, theMainWindow):
super(UiMainWindow, self).__init__()
self.HuntTab = QtWidgets.QWidget()
self.uiHunt = UiHuntTab(self.HuntTab)
self.centralwidget = QtWidgets.QWidget(theMainWindow)
self.MainWindow = theMainWindow
self.statusbar = QtWidgets.QStatusBar(theMainWindow)
self.menubar = QtWidgets.QMenuBar(theMainWindow)
self.Love = QtWidgets.QPushButton(self.centralwidget)
self.Life = QtWidgets.QPushButton(self.centralwidget)
self.Rule = QtWidgets.QPushButton(self.centralwidget)
self.Hunt = QtWidgets.QPushButton(self.centralwidget)
self.Fight = QtWidgets.QPushButton(self.centralwidget)
self.Shop = QtWidgets.QPushButton(self.centralwidget)
self.MainOutput = QtWidgets.QLabel(self.centralwidget)
self.iniUI()
def iniUI(self):
self.Hunt.clicked.connect(self.CallHutTab)
def CallHutTab(self):
self.uiHunt.setupUi(self.HuntTab)
self.HuntTab.show()
def setupUi(self, theMainWindow):
theMainWindow.setObjectName("MainWindow")
theMainWindow.resize(519, 404)
self.centralwidget.setObjectName("centralwidget")
self.MainOutput.setGeometry(QtCore.QRect(40, 30, 131, 171))
self.MainOutput.setIndent(0)
self.MainOutput.setObjectName("MainOutput")
self.Shop.setGeometry(QtCore.QRect(40, 230, 141, 51))
self.Shop.setObjectName("Shop")
self.Fight.setGeometry(QtCore.QRect(190, 230, 141, 51))
self.Fight.setObjectName("Fight")
self.Hunt.setGeometry(QtCore.QRect(340, 230, 141, 51))
self.Hunt.setObjectName("Hunt")
self.Rule.setGeometry(QtCore.QRect(190, 290, 141, 51))
self.Rule.setObjectName("Rule")
self.Life.setGeometry(QtCore.QRect(340, 290, 141, 51))
self.Life.setObjectName("Life")
self.Love.setGeometry(QtCore.QRect(40, 290, 141, 51))
self.Love.setObjectName("Love")
theMainWindow.setCentralWidget(self.centralwidget)
self.menubar.setGeometry(QtCore.QRect(0, 0, 519, 21))
self.menubar.setObjectName("menubar")
theMainWindow.setMenuBar(self.menubar)
self.statusbar.setObjectName("statusbar")
theMainWindow.setStatusBar(self.statusbar)
self.retranslateUi(theMainWindow)
QtCore.QMetaObject.connectSlotsByName(theMainWindow)
def retranslateUi(self, theMainWindow):
_translate = QtCore.QCoreApplication.translate
theMainWindow.setWindowTitle(_translate("MainWindow", "Fight"))
self.MainOutput.setText(_translate("MainWindow", self.UI))
self.Shop.setText(_translate("MainWindow", "Shop"))
self.Fight.setText(_translate("MainWindow", "Fight"))
self.Hunt.setText(_translate("MainWindow", "Hunt"))
self.Rule.setText(_translate("MainWindow", "Rule"))
self.Life.setText(_translate("MainWindow", "Your Life"))
self.Love.setText(_translate("MainWindow", "Love"))
class UiHuntTab(object):
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
def __init__(self, HuntTab):
super(UiHuntTab, self).__init__()
self.HuntPotions = QtWidgets.QPushButton(HuntTab)
self.HuntHide = QtWidgets.QPushButton(HuntTab)
self.HuntDefend = QtWidgets.QPushButton(HuntTab)
self.HuntAttack = QtWidgets.QPushButton(HuntTab)
self.HuntTabOutput = QtWidgets.QLabel(HuntTab)
self.iniUi()
def iniUi(self):
self.HuntAttack.clicked.connect(self.Attack)
self.HuntHide.clicked.connect(self.Hide)
def Attack(self):
global hp
global enemyHp
global exp
if hp > 0:
attack = random.randrange(attackMin, attackMax + 1, 1)
enAttack = random.randrange(enemyAttackMin, enemyAttackMax + 1, 1)
hp -= enAttack
enemyHp -= attack
if enemyHp < 1:
exp += enemyLevel * 20
self.NewEnemy()
if exp >= expMax:
self.LevelUp()
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
if hp < 1:
hp = 0
# Death Death Death Death Death Death Death Death
def Hide(self):
global hp
if hp > 0:
hp += 5
if hp >= hpMax:
hp = hpMax
prob = random.randrange(1, 11, 1)
if prob == 5:
hp -= random.randrange(enemyAttackMin, enemyAttackMax, 1)
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def LevelUp(self):
global level
global attackMax
global attackMin
global expMax
global exp
global hpMax
global hp
level += 1
expMax = (level - 1) * 200
hpMax += 20
hp = hpMax
attackMax += random.randrange(1, 3, 1)
attackMin += random.randrange(1, 3, 1)
exp = 0
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def NewEnemy(self):
global enemyLevel
global enemyHp
global enemyAttackMax
global enemyAttackMin
enemyLevel = random.randrange(1, 4, 1) * level
enemyHp = enemyLevel * 20 + 20
enemyAttackMax = random.randrange(2, 4, 1) * enemyLevel
enemyAttackMin = random.randrange(1, 3, 1) * enemyLevel
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def setupUi(self, HuntTab):
HuntTab.setObjectName("HuntTab")
HuntTab.resize(379, 263)
self.HuntTabOutput.setGeometry(QtCore.QRect(30, 30, 150, 101))
self.HuntTabOutput.setObjectName("HuntTabOutput")
self.HuntAttack.setGeometry(QtCore.QRect(30, 140, 91, 41))
self.HuntAttack.setObjectName("HuntAttack")
self.HuntDefend.setGeometry(QtCore.QRect(140, 140, 91, 41))
self.HuntDefend.setObjectName("HuntDefend")
self.HuntHide.setGeometry(QtCore.QRect(250, 140, 91, 41))
self.HuntHide.setObjectName("HuntHide")
self.HuntPotions.setGeometry(QtCore.QRect(140, 190, 91, 41))
self.HuntPotions.setObjectName("HuntPotions")
self.retranslateUi(HuntTab)
QtCore.QMetaObject.connectSlotsByName(HuntTab)
def retranslateUi(self, HuntTab):
_translate = QtCore.QCoreApplication.translate
HuntTab.setWindowTitle(_translate("HuntTab", "Hunt"))
self.HuntTabOutput.setText(_translate("HuntTab", self.uiText))
self.HuntAttack.setText(_translate("HuntTab", "Attack"))
self.HuntDefend.setText(_translate("HuntTab", "Defend"))
self.HuntHide.setText(_translate("HuntTab", "Hide"))
self.HuntPotions.setText(_translate("HuntTab", "Potions"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = UiMainWindow(MainWindow)
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
It Was Easier than I Expected, In the class UiHuntTab and In __init__ I just Added self.HuntTabWindow = HuntTab And when i want to close the HuntTab i only needed to call self.HuntTabWindow.close()
class UiHuntTab(object):
def __init__(self, HuntTab):
super(UiHuntTab, self).__init__()
self.HuntTabWindow = HuntTab
self.HuntPotions = QtWidgets.QPushButton(HuntTab)
self.HuntHide = QtWidgets.QPushButton(HuntTab)
self.HuntDefend = QtWidgets.QPushButton(HuntTab)
self.HuntAttack = QtWidgets.QPushButton(HuntTab)
self.HuntTabOutput = QtWidgets.QLabel(HuntTab)
self.iniUi()
a
if hp < 1:
self.HuntTabWindow.close()
And if I Wanted to Close the MainWindow self.MainWindow = MainWindow and self.MainWindow.close()
Related
I'm new to pyqt and trying to make a degrees converter application. Now I want to make the text resizable, when I resize MainWindow.
The code:
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtWidgets.QMainWindow):
def resizeEvent(self, event):
print("Window has been resized")
QtWidgets.QMainWindow.resizeEvent(self, event)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(305, 250)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(305, 250))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../Users/Midgetfucker/Downloads/temperature.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(False)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.lineEdit_input = QtWidgets.QLineEdit(parent=self.centralwidget)
self.lineEdit_input.setStyleSheet("")
self.lineEdit_input.setLocale(QtCore.QLocale(QtCore.QLocale.Language.Russian, QtCore.QLocale.Country.Russia))
self.lineEdit_input.setObjectName("lineEdit_input")
self.gridLayout_3.addWidget(self.lineEdit_input, 0, 1, 1, 1)
self.label_fahrenheit = QtWidgets.QLabel(parent=self.centralwidget)
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.label_fahrenheit.setFont(font)
self.label_fahrenheit.setObjectName("label_fahrenheit")
self.gridLayout_3.addWidget(self.label_fahrenheit, 0, 0, 1, 1)
self.plainTextEdit_output = QtWidgets.QPlainTextEdit(parent=self.centralwidget)
self.plainTextEdit_output.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
self.plainTextEdit_output.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
self.plainTextEdit_output.setObjectName("plainTextEdit_output")
self.gridLayout_3.addWidget(self.plainTextEdit_output, 1, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.add_functions()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Преобразователь температур"))
self.label_fahrenheit.setText(_translate("MainWindow", "Градусы:"))
def add_functions(self):
self.lineEdit_input.textChanged.connect(self.degrees_changed)
def degrees_changed(self):
self.plainTextEdit_output.setPlainText("")
self.plainTextEdit_output.setStyleSheet("")
degrees = self.lineEdit_input.text()
if degrees == '':
return
degrees = degrees.replace(',', '.')
try:
degrees = float(degrees)
except ValueError:
self.plainTextEdit_output.setPlainText("Некорректный ввод")
self.plainTextEdit_output.setStyleSheet("color: rgb(255, 0, 0);")
self.lineEdit_input.setFocus()
return
f_to_c = round((degrees * 9/5 + 32), 2)
f_to_k = round((degrees - 32) * 5/9 + 273.15, 2)
c_to_f = round((degrees - 32) * 5/9, 2)
c_to_k = round(degrees + 273.15, 2)
k_to_f = round((degrees - 273.15) * 9/5 + 32, 2)
k_to_c = round(degrees - 273.15, 2)
if round(f_to_c) == f_to_c:
f_to_c = int(f_to_c)
if round(f_to_k) == f_to_k:
f_to_k = int(f_to_k)
if round(c_to_f) == c_to_f:
c_to_f = int(c_to_f)
if round(c_to_k) == c_to_k:
c_to_k = int(c_to_k)
if round(k_to_f) == k_to_f:
k_to_f = int(k_to_f)
if round(k_to_c) == k_to_c:
k_to_c = int(k_to_c)
if round(degrees) == degrees:
degrees = int(degrees)
f_to_c = str(f_to_c)
f_to_k = str(f_to_k)
c_to_f = str(c_to_f)
c_to_k = str(c_to_k)
k_to_c = str(k_to_c)
k_to_f = str(k_to_f)
degrees = str(degrees)
self.plainTextEdit_output.setPlainText('°F: \n'
+ degrees + '°F = ' + f_to_c + '°C' + '\n'
+ degrees + '°F = ' + f_to_k + '°K' + '\n\n'
+ '°C: \n'
+ degrees + '°C = ' + c_to_f + '°F' + '\n'
+ degrees + '°C = ' + c_to_k + '°K' + '\n\n'
+ '°K: \n'
+ degrees + '°K = ' + k_to_f + '°F' + '\n'
+ degrees + '°K = ' + k_to_c + '°C')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec())
I've already tried this, but doesn't work for me. Any hints or ideas pls?
Windows 10
Using Qt Designer with PyCharm
This question already has answers here:
time.sleep() and BackGround Windows PyQt5
(1 answer)
Equivalent to time.sleep for a PyQt application
(5 answers)
Closed 2 years ago.
I have created a big project involving communication with a controller via serial port.
My project is divided to 3 files:
File A - a pyqt5 designer file - including all my buttons, line edits, etc.
File B - a serial communication file - basically ask questions and receive answers from the controller.
File C - the main file; in this file I am importing file A and file B and using them.
In file C, I have created a worker, so all the communications with the controller are being made by this thread. (using the class and functions of file B..)
Now, I am trying to make a create a new function within the worker. The functions is using time.sleep every x seconds for y times. From what I understand, because I am using a thread, the GUI should not get stuck, but for some reason, it does.
Since the code is very long, I have only attaching what I think is relevant to the question.
I tried to copy as little of the code, yet still keep it understandable, I hope it's ok.
File A - pyqt5 designer code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
################creating general veriables#####################
MainWindow.setObjectName("MainWindow")
MainWindow.setFixedSize(780, 585)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame_Holder = QtWidgets.QFrame(self.centralwidget)
self.frame_Holder.setGeometry(QtCore.QRect(0, 85, 780, 500))
self.frame_Holder.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_Holder.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Holder.setObjectName("frame_Holder")
#########################################################################
################creating veriables for the Top Frame#####################
self.frame_Top = QtWidgets.QFrame(self.centralwidget)
self.frame_Top.setEnabled(True)
self.frame_Top.setGeometry(QtCore.QRect(10, 5, 760, 80))
font = QtGui.QFont()
font.setStrikeOut(False)
self.frame_Top.setFont(font)
self.frame_Top.setFrameShape(QtWidgets.QFrame.WinPanel)
self.frame_Top.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Top.setLineWidth(1)
self.frame_Top.setObjectName("frame_Top")
################creating Buttons#####################
self.btn_Connect = QtWidgets.QPushButton(self.frame_Top)
self.btn_Connect.setGeometry(QtCore.QRect(85, 50, 75, 23))
self.btn_Connect.setObjectName("btn_Connect")
self.btn_Connect.setEnabled(False)
self.btn_PortList = QtWidgets.QPushButton(self.frame_Top)
self.btn_PortList.setGeometry(QtCore.QRect(10, 50, 65, 23))
self.btn_PortList.setObjectName("btn_PortList")
self.productMenu=QtWidgets.QMenu(self.frame_Top)
self.btn_PortList.setMenu(self.productMenu)
self.btn_Init = QtWidgets.QPushButton(self.frame_Top)
self.btn_Init.setEnabled(False)
self.btn_Init.setGeometry(QtCore.QRect(300, 50, 75, 23))
self.btn_Init.setObjectName("btn_Init")
################creating text edits#####################
self.edit_version = QtWidgets.QLineEdit(self.frame_Top)
self.edit_version.setGeometry(QtCore.QRect(170, 50, 120, 23))
self.edit_version.setObjectName("edit_version")
self.edit_version.setEnabled(False)
################creating labels#####################
self.lbl_Version = QtWidgets.QLabel(self.frame_Top)
self.lbl_Version.setGeometry(QtCore.QRect(170, 30, 71, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.lbl_Version.setFont(font)
self.lbl_Version.setObjectName("lbl_Version")
self.lbl_FrameTop = QtWidgets.QLabel(self.frame_Top)
self.lbl_FrameTop.setEnabled(True)
self.lbl_FrameTop.setGeometry(QtCore.QRect(5, 5, 90, 25))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
font.setStrikeOut(False)
font.setKerning(True)
self.lbl_FrameTop.setFont(font)
self.lbl_FrameTop.setObjectName("lbl_FrameTop")
self.lbl_On = QtWidgets.QLabel(self.frame_Top)
self.lbl_On.setGeometry(QtCore.QRect(528, 30, 41, 16))
self.lbl_On.setObjectName("lbl_On")
self.lbl_Enable = QtWidgets.QLabel(self.frame_Top)
self.lbl_Enable.setGeometry(QtCore.QRect(560, 30, 41, 16))
self.lbl_Enable.setObjectName("lbl_Enable")
self.lbl_Rls = QtWidgets.QLabel(self.frame_Top)
self.lbl_Rls.setGeometry(QtCore.QRect(608, 30, 41, 16))
self.lbl_Rls.setObjectName("lbl_Rls")
self.lbl_Chk = QtWidgets.QLabel(self.frame_Top)
self.lbl_Chk.setGeometry(QtCore.QRect(645, 30, 41, 16))
self.lbl_Chk.setObjectName("lbl_Chk")
self.lbl_Wafer = QtWidgets.QLabel(self.frame_Top)
self.lbl_Wafer.setGeometry(QtCore.QRect(683, 30, 41, 16))
self.lbl_Wafer.setObjectName("lbl_Wafer")
self.lbl_Err = QtWidgets.QLabel(self.frame_Top)
self.lbl_Err.setGeometry(QtCore.QRect(725, 30, 20, 16))
self.lbl_Err.setObjectName("lbl_Err")
self.lbl_Port = QtWidgets.QLabel(self.frame_Top)
self.lbl_Port.setGeometry(QtCore.QRect(10, 30, 51, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.lbl_Port.setFont(font)
self.lbl_Port.setObjectName("lbl_Port")
#########################################################################
self.frame_AutoRun = QtWidgets.QFrame(self.frame_Holder)
self.frame_AutoRun.setEnabled(False)
self.frame_AutoRun.setGeometry(QtCore.QRect(10, 90, 760, 320))
font = QtGui.QFont()
self.frame_AutoRun.setFont(font)
self.frame_AutoRun.setFrameShape(QtWidgets.QFrame.WinPanel)
self.frame_AutoRun.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_AutoRun.setLineWidth(1)
self.frame_AutoRun.setObjectName("frame_AutoRun")
self.lbl_AutoRun = QtWidgets.QLabel(self.frame_AutoRun)
self.lbl_AutoRun.setGeometry(QtCore.QRect(5, 5, 110, 25))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
font.setStrikeOut(False)
font.setKerning(True)
self.lbl_AutoRun.setFont(font)
self.lbl_AutoRun.setObjectName("lbl_AutoRun")
self.btn_RunStop = QtWidgets.QPushButton(self.frame_AutoRun)
self.btn_RunStop.setGeometry(QtCore.QRect(500, 40, 60, 23))
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(False)
font.setWeight(50)
font.setKerning(True)
self.btn_RunStop.setFont(font)
self.btn_RunStop.setObjectName("btn_RunStop")
########################4##########################
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ECC GUI"))
self.btn_Connect.setText(_translate("MainWindow", "Connect"))
self.btn_PortList.setText(_translate("MainWindow", "Ports"))
self.lbl_Version.setText(_translate("MainWindow", "Version"))
self.btn_Init.setText(_translate("MainWindow", "Initiate"))
self.lbl_FrameTop.setText(_translate("MainWindow", "Connect"))##########
self.lbl_Port.setText(_translate("MainWindow", "Ports"))
self.lbl_On.setText(_translate("MainWindow", "ON"))
self.lbl_Enable.setText(_translate("MainWindow", "Enable"))
self.lbl_Rls.setText(_translate("MainWindow", "RLS"))
self.lbl_Chk.setText(_translate("MainWindow", "CHK"))
self.lbl_Wafer.setText(_translate("MainWindow", "Wafer"))
self.lbl_Err.setText(_translate("MainWindow", "ERR"))
self.lbl_AutoRun.setText(_translate("MainWindow", "Auto Run"))
self.btn_RunStop.setText(_translate("MainWindow", "Run"))
File B - the serial communication file
import serial
from string import hexdigits
from re import search
class ECC():
def __init__(self,Port ):
self.ser = serial.Serial(port ='COM'+str(Port), baudrate= 38400,timeout=1)
def cmd(self,command):
return ('00'+command+chr(13)).encode('utf-8')
def disconnect(self):
self.ser.close()
def init(self):
self.ser.write(self.cmd('INI'))
return(self.ser.readline().decode('utf-8')[:3])
def spr(self,address,value):
self.ser.write(self.cmd('SPR'+str(address)+str(value)))
return (self.ser.readline().decode('utf-8')[:3])
def rpr(self,address):
self.ser.write(self.cmd('RPR'+str(address)))
return(self.ser.readline().decode('utf-8')[3:7])
def chuck(self):
self.ser.write(self.cmd('CHK'))
return(self.ser.readline().decode('utf-8')[:3])
def rls(self):
self.ser.write(self.cmd('RLS'))
return(self.ser.readline().decode('utf-8')[:3])
def cap(self):
self.ser.write(self.cmd('cap'))
cap=self.ser.readline()[3:].decode('utf-8')
cap=cap.rstrip()
if (all(c in hexdigits for c in cap) and cap!=""):
return int(cap,16)
else:
return("Busy...")
def version(self):
self.ser.write(self.cmd('VER'))
return(self.ser.readline().decode('utf-8')[:9])
def gst(self):
self.ser.flushInput()
self.ser.flushOutput()
self.ser.write(self.cmd('GST'))
gst=self.ser.readline()
gst=gst.decode('utf-8')
is_STV=search('^STV',str(gst))
if (is_STV):
stat_hex=gst[3:]
stat_bin=(bin(int(stat_hex,16))[2:].zfill(16))
stat_bool=[bool(int(bit)) for bit in stat_bin]
else:
stat_hex="ERR"
stat_bool="ERR"
return stat_hex, stat_bool
def statLights(self):
[stat_hex, stat_bool]=self.gst()
if(not stat_hex=="ERR"):
lights=[not(stat_bool[3]),not(stat_bool[5]),not(stat_bool[10]),stat_bool[10],stat_bool[11],stat_bool[0]]
else:
lights="ERR"
return lights
def msrphys(self):
self.ser.flushInput()
self.ser.flushOutput()
self.ser.write(self.cmd('msr'))
A=list()
A.append(self.ser.readline())
A[0]=A[0][3:7]
exists=search('[0-9A-Fa-f]{4}',str(A[0]))
if(exists):
A[0]=int(A[0],16)*-0.08398628+2500
for ind in range(1,32):
A.append(self.ser.readline())
exists=search('[0-9A-Fa-f]{4}',str(A[ind]))
if (exists):
A[ind]=int(A[ind].decode('utf-8'),16)*-0.08398628+2500
else:
A[0]="ERR"
break
self.ser.readline()
A[12]=A[12]*5.75
A[13]=A[13]*5.75
A[14]=A[14]*0.1
else:
A[0]="ERR"
return A
File C - the operative file
from test_des import Ui_MainWindow
from PyQt5 import QtWidgets, QtCore, QtGui
from test_serialCom import ECC
import serial.tools.list_ports
import sys
from re import findall
import time
from functools import partial
try:
import queue
except ImportError:
import Queue as queue
class eccWorker(QtCore.QRunnable):
def __init__(self,port,q):
super(eccWorker, self).__init__()
self.finished = QtCore.pyqtSignal()
self.port=port
self.Q=q
self.threadactive=True
def run(self):
if(self.threadactive==True):
try:
self.ecc=ECC(self.port)
except:
self.threadactive=False
self.Q.put("ERROR-Not connected")
self.Q.put("ERROR-Not connected")
else:
self.Q.put(self.ecc.version())
self.Q.put(self.ecc.rpr('04'))
def init(self):
if(self.threadactive):
self.ecc.init()
def disconnect(self):
self.ecc.disconnect()
self.threadactive=False
def readCap(self):
if(self.threadactive==True):
self.Q.put(self.ecc.cap())
def chk(self):
if(self.threadactive==True):
self.ecc.chuck()
def rls(self):
if(self.threadactive==True):
self.ecc.rls()
def rprWorker(self,par):
if(self.threadactive==True):
self.Q.put(self.ecc.rpr(par))
def sprWorker(self,par,val):
if(self.threadactive==True):
# par=par.zfill(2)
isOk=self.ecc.spr(par,val)
if (isOk!="NAK"):
self.Q.put(self.ecc.rpr(par))
def getStat(self):
if(self.threadactive==True):
statLight=self.ecc.statLights()
if(statLight=="ERR"):
self.Q.put("ERR")
else:
for i in statLight:
self.Q.put(i)
def sprWorkerNoRpr(self,par,val):
if(self.threadactive==True):
isOk=self.ecc.spr(par,val)
if (isOk!="NAK"):
return True
def test1(self,Vchk,N,dt,Dt,threshold):
Vchk=str(Vchk).zfill(4)
if(self.sprWorkerNoRpr('04',Vchk)):
cap1=list()
cap2=list()
for i in range(N):
self.rls()
time.sleep(dt)
self.readCap()
res=self.Q.get()
if (res!="Busy..."):
cap1.append(int(str(res)))
time.sleep(Dt)
self.chk()
time.sleep(dt)
self.readCap()
res2=self.Q.get()
if (res2!="Busy..."):
cap2.append(int(str(res2)))
time.sleep(Dt)
self.rls()
cap_Rls=sum(cap1)/len(cap1)
cap_Chk=sum(cap2)/len(cap2)
if((max(cap2)-min(cap1))>threshold):
isPass=True
else:
isPass=False
self.Q.put(cap_Rls)
self.Q.put(cap_Chk)
self.Q.put(isPass)
print("Done!")
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.threadpool=QtCore.QThreadPool()
self.Q=queue.Queue()
self.ui.productMenu.aboutToShow.connect(self.findPort)
self.ui.btn_Connect.clicked.connect(self.connectClicked)
self.ui.btn_RunStop.clicked.connect(self.run)
self.ui.btn_Init.clicked.connect(self.initClicked)
self.redOff=QtGui.QColor(120,0,0)
self.redOn=QtGui.QColor(255,0,0)
self.grnOff=QtGui.QColor(7,100,0)
self.grnOn=QtGui.QColor(16,243,0)
self.yelOff=QtGui.QColor(155,80,0)
self.yelOn=QtGui.QColor(255,127,0)
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
def paintEvent(self, e):
onLedPainter = QtGui.QPainter(self)
onLedPainter.setPen(self.onPen)
onLedPainter.setBrush(self.grnOff)
onLedPainter.drawEllipse(540,55,10,10)
enabledLedPainter = QtGui.QPainter(self)
enabledLedPainter.setPen(self.enablePen)
enabledLedPainter.setBrush(self.grnOff)
enabledLedPainter.drawEllipse(580,55,10,10)
rlsLedPainter = QtGui.QPainter(self)
rlsLedPainter.setPen(self.rlsPen)
rlsLedPainter.setBrush(self.grnOff)
rlsLedPainter.drawEllipse(620,55,10,10)
chkLedPainter = QtGui.QPainter(self)
chkLedPainter.setPen(self.chkPen)
chkLedPainter.setBrush(self.grnOff)
chkLedPainter.drawEllipse(660,55,10,10)
waferLedPainter = QtGui.QPainter(self)
waferLedPainter.setPen(self.waferPen)
waferLedPainter.setBrush(self.yelOff)
waferLedPainter.drawEllipse(700,55,10,10)
errLedPainter = QtGui.QPainter(self)
errLedPainter.setPen(self.errPen)
errLedPainter.setBrush(self.redOff)
errLedPainter.drawEllipse(740,55,10,10)
def updateStat(self):
#####updating LEDs####
self.worker.getStat()
self.ledStat=list()
self.ledStat.append(self.worker.Q.get())
if(not self.ledStat[0]=="ERR"):
for i in range(5):
self.ledStat.append(self.worker.Q.get())
if(self.ledStat[0]):
self.onPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
else:
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[1]):
self.enablePen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
else:
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[2]):
self.rlsPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
else:
self.chkPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[4]):
self.waferPen=QtGui.QPen(self.yelOn, 8, QtCore.Qt.SolidLine)
else:
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[5]):
self.errPen=QtGui.QPen(self.redOn, 8, QtCore.Qt.SolidLine)
else:
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
self.update()
else:
self.connectClicked()
self.ui.edit_version.setText("GST Disconnected!")
def findPort(self):
self.ui.productMenu.clear()
comPorts = list(serial.tools.list_ports.comports()) # get a list of all devices connected through serial port
comPorts=sorted(comPorts)
for port in comPorts:
self.ui.productMenu.addAction(str(port),self.selectedPort)
def selectedPort(self):
self.portNum=self.sender()
self.portNum=self.portNum.text()
self.portNum=findall("COM\d+",self.portNum)
self.ui.btn_PortList.setText(str(self.portNum[0]))
self.portNum=self.portNum[0][3:]
self.ui.btn_Connect.setEnabled(True)
def connectClicked(self):
if (self.ui.btn_Connect.text()=="Connect"):
self.worker=eccWorker(self.portNum,self.Q)
self.threadpool.start(self.worker)
ver=self.worker.Q.get()
volHex=self.worker.Q.get()
if(ver[:3]=="VER"):
self.ui.btn_Connect.setText("Disconnect")
self.ui.btn_PortList.setEnabled(False)
self.ui.edit_version.setText(ver)
self.ui.btn_Init.setEnabled(True)
self.ui.frame_AutoRun.setEnabled(True)
self.timer_updateStat = QtCore.QTimer()
self.timer_updateStat.setInterval(500)
self.timer_updateStat.timeout.connect(self.updateStat)
self.timer_updateStat.start()
else:
self.ui.edit_version.setText("Error!")
else:
self.timer_updateStat.stop()
self.worker.disconnect()
self.ui.btn_Connect.setText("Connect")
self.ui.btn_Connect.setEnabled(False)
self.ui.btn_Init.setEnabled(False)
self.ui.frame_AutoRun.setEnabled(False)
self.ui.btn_PortList.setEnabled(True)
self.ui.edit_version.clear()
self.setFixedSize(780,585)
self.ui.btn_PortList.setText("Ports")
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
self.update()
def initClicked(self):
self.worker.init()
def run(self):
self.worker.test1(200,5,0.2,0.3,100)
cap_Rls=self.Q.get()
cap_Chk=self.Q.get()
ispass=self.Q.get()
print("cap_Rls:\n")
print(cap_Rls)
print("cap_Chk:\n")
print(cap_Chk)
print(ispass)
def closeEvent(self,event):
try:
self.worker.disconnect()
finally:
sys.exit()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
So what does the GUI gets stuck for the time of the function even though I am using a thread? What can I do to fix this?
Also, ideally, I would want to have another file, file D, that contains a main class called TESTS,and it has like 5 functions within it, each one represents a test.
The problem I faced doing the above, is failing to calling/getting information from the thread active in file C, so if you have an idea of how to make this one as well, it would be much appreciated. (if not creating another file, so store all the tests in a different class. Here, as well, I faced some issues and could not make it work).
After many many hours of searching online, I found that using QtTest.QTest.qWait(msecs)
instead of sleep is giving me the wanted result - it holds the commands but does not make the GUI freeze.
In order to use it I had to use from PyQt5 import QtTest.
If anyone has yet a better suggestions (to any of the questions above) I would love to see them.
I have seen some information posted about this, but everything seems to be with PyQt4 not PyQt5 and I'm not sure if there is a difference. I couldn't get anything to work.
What I want to do is have the program update a QLabel after the user inputs text into it and saves it. Right now I have the main window, with either a button or a selection from a drop down menu that will pop up a window with the ability to change setpoints.
Now what happens is the user can put in new data, but the code seems to still run and not wait for the user to make a change in the popup. calling my updateSetpoints function before anything changes.
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
A button calls reactorSetpoints(self) and popups a new window
import sys
import matplotlib.pyplot as plt
import random
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication,QLineEdit, QPushButton, QWidget, QDialog, QTextEdit, QLabel, QMenu, QVBoxLayout, QSizePolicy
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt, QTime, QTimer, QRect
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
debug = True
setPointsChanged = False
versionNumber = 'V0.0.1'
currentState = 'Treatment'
currentCycTime = '2:15:42'
remaningCycTime = '5:44:18'
current_pH = 6.85
current_DO = 1.90
currentTemp = 24.9
lower_pH = 6.95
upper_pH = 7.20
lower_DO = 2.00
def openFile():
if debug == True:
print("Open File")
def saveFile():
if debug == True:
print("Save File")
def saveFileAs():
if debug == True:
print("Save File As...")
def editSysParm():
if debug == True:
print("Edit system parameters")
def reactorParameters():
if debug == True:
print("Edit reactor parameters")
def pHCalibration():
if debug == True:
print("pH Calibration")
def dOCalibration():
if debug == True:
print("DO calibration")
def pumpCalibration():
if debug == True:
print("Pump calibrations")
def editpHSetpoints():
pass
# sets up the setpoints popup window with either the option to save
# new setpoints, or to quit
class setpointsPopup(QDialog):
def __init__(self, parent = None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.setGeometry(100,100,300,300)
self.upH = QLabel('Upper pH: ',self)
self.lpH = QLabel('Lower pH: ',self)
self.lDO = QLabel('Lower DO: ',self)
self.upHE = QLineEdit(self)
self.lpHE = QLineEdit(self)
self.lDOE = QLineEdit(self)
self.upHE.setPlaceholderText(str(upper_pH))
self.lpHE.setPlaceholderText(str(lower_pH))
self.lDOE.setPlaceholderText(str(lower_DO))
self.exitSetpoints = QPushButton('Exit', self)
self.saveSetpoints = QPushButton('Save New Setpoints', self)
self.upH.move(5,5)
self.upHE.move(90,5)
self.lpH.move(5,40)
self.lpHE.move(90,40)
self.lDO.move(5,75)
self.lDOE.move(90,75)
self.exitSetpoints.setGeometry(QRect(5,120,50,30))
self.exitSetpoints.clicked.connect(self.destroy)
self.saveSetpoints.setGeometry(QRect(60,120,150,30))
self.saveSetpoints.clicked.connect(self.verifySetpoints)
self.show()
#verification will be put here to make sure the input is valid
#but for now it will accept anything for ease of testing
def verifySetpoints(self):
global upper_pH
newUpH = self.upHE.text()
upper_pH = float(newUpH)
print(newUpH)
# Main window
class drawMenuBar(QMainWindow):
def __init__(self):
super().__init__()
self.topL = 20
self.top = 40
self.width = 1000
self.height = 500
self.title = ('Batch Reactor Controller ' + versionNumber)
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.topL, self.top, self.width, self.height)
exitAct = QAction('&Exit' , self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit Application')
exitAct.triggered.connect(qApp.quit)
openAct = QAction('&Open', self)
openAct.setShortcut('Ctrl+O')
openAct.setStatusTip('Open File')
openAct.triggered.connect(openFile)
saveAsAct = QAction('&Save As..', self)
saveAsAct.setShortcut('Shift+Ctrl+S')
saveAsAct.setStatusTip('Save as new file')
saveAsAct.triggered.connect(saveFileAs)
saveAct = QAction('Save', self)
saveAct.setStatusTip('Save')
saveAct.setShortcut('Ctrl+S')
saveAct.triggered.connect(saveFile)
systemSetpointsAct = QAction('Preferences', self)
systemSetpointsAct.setStatusTip('Edit system parameters')
systemSetpointsAct.triggered.connect(editSysParm)
reactorSetpointsAct = QAction('Reactor Setpoints', self)
reactorSetpointsAct.setStatusTip('Edit reactor setpoints')
reactorSetpointsAct.triggered.connect(self.reactorSetpoints)
reactorParametersAct = QAction('Reactor Parameters', self)
reactorParametersAct.setStatusTip('Edit batch reactor profiles')
reactorParametersAct.triggered.connect(reactorParameters)
pHCalibrationAct = QAction('pH Calibration', self)
pHCalibrationAct.setStatusTip('pH Calibration')
pHCalibrationAct.triggered.connect(pHCalibration)
dOCalibrationAct = QAction('DO Calibration', self)
dOCalibrationAct.setStatusTip('Dissolved oxygen calibration')
dOCalibrationAct.triggered.connect(dOCalibration)
pumpCalibrationAct = QAction('Pump Calibrations', self)
pumpCalibrationAct.setStatusTip('Pump Calibrations')
pumpCalibrationAct.triggered.connect(pumpCalibration)
menubar = self.menuBar()
self.statusBar()
fileMenu = menubar.addMenu('&File')
editMenu = menubar.addMenu('&Edit')
calibrationMenu = menubar.addMenu('&Calibration')
fileMenu.addAction(openAct)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
fileMenu.addAction(exitAct)
calibrationMenu.addAction(pHCalibrationAct)
calibrationMenu.addAction(dOCalibrationAct)
calibrationMenu.addAction(pumpCalibrationAct)
editMenu.addAction(systemSetpointsAct)
editMenu.addAction(reactorSetpointsAct)
self.reactorTitle = QLabel('<b><u>Reactor 1 Status</u></b>', self)
font = self.reactorTitle.font()
font.setPointSize(20)
self.reactorTitle.setFont(font)
self.reactorTitle.setGeometry(QtCore.QRect(10,30, 250, 45)) #(x, y, width, height)
#pH Label
self.pHLabel = QLabel('<span style="color:blue"><b>pH:</b></span>',self)
font = self.pHLabel.font()
font.setPointSize(22)
self.pHLabel.setFont(font)
self.pHLabel.setGeometry(QtCore.QRect(10,50,100,100))
#displays current pH value
self.currentpH = QLabel('<b>' + str(current_pH) + '</b>', self)
font = self.currentpH.font()
font.setPointSize(22)
self.currentpH.setFont(font)
self.currentpH.setGeometry(QtCore.QRect(60,50,100,100))
#display lowerpH Setpoint
self.pHLowerLabel = QLabel('Lower pH setpoint: ', self)
font = self.pHLowerLabel.font()
font.setPointSize(10)
self.pHLowerLabel.setFont(font)
self.pHLowerLabel.setGeometry(QtCore.QRect(10, 105, 115, 50))
self.pHLowerValue = QLabel('{0:0.2f}'.format(lower_pH), self)
font = self.pHLowerValue.font()
font.setPointSize(10)
self.pHLowerValue.setFont(font)
self.pHLowerValue.setGeometry(QtCore.QRect(120, 105, 50, 50))
#display upper pH setpoint
self.pHUpperLabel = QLabel('Upper pH setpoint: ', self)
font = self.pHUpperLabel.font()
font.setPointSize(10)
self.pHUpperLabel.setFont(font)
self.pHUpperLabel.setGeometry(QtCore.QRect(10, 120, 115, 50))
self.pHUpperValue = QLabel('{0:0.2f}'.format(upper_pH), self)
font = self.pHUpperValue.font()
font.setPointSize(10)
self.pHUpperValue.setFont(font)
self.pHUpperValue.setGeometry(QtCore.QRect(120, 120, 50, 50))
#pH button options
self.pHToGraph = QPushButton('Graph pH', self)
self.pHToGraph.move(10,160)
self.pHToGraph.setToolTip('Show pH in live graph')
self.pHToGraph.clicked.connect(self.displaypHGraph)
self.pHSetpointsButton = QPushButton('Update Setpoints', self)
self.pHSetpointsButton.setGeometry(QtCore.QRect(115, 160, 150, 30))
self.pHSetpointsButton.setToolTip('Edit pH Setpoints')
self.pHSetpointsButton.clicked.connect(self.reactorSetpoints)
self.DOLabel = QLabel('<span style="color:blue"><b>DO:</b></span>',self)
font = self.DOLabel.font()
font.setPointSize(22)
self.DOLabel.setFont(font)
self.DOLabel.setGeometry(QtCore.QRect(10,175,100,100))
self.currentDO = QLabel('<b>' + str(current_DO) + ' mg/L</b>', self)
font = self.currentDO.font()
font.setPointSize(22)
self.currentDO.setFont(font)
self.currentDO.setGeometry(QtCore.QRect(60,175,150,100))
self.DOLowerLabel = QLabel('Lower DO setpoint: ', self)
font = self.DOLowerLabel.font()
font.setPointSize(10)
self.DOLowerLabel.setFont(font)
self.DOLowerLabel.setGeometry(QtCore.QRect(10, 225, 115, 50))
self.DOLowerValue = QLabel('{0:0.2f}'.format(lower_DO) + ' mg/L', self)
font = self.DOLowerValue.font()
font.setPointSize(10)
self.DOLowerValue.setFont(font)
self.DOLowerValue.setGeometry(QtCore.QRect(120, 225, 75, 50))
self.DOToGraph = QPushButton('Graph DO', self)
self.DOToGraph.move(10,260)
self.DOToGraph.setToolTip('Show DO in live graph')
self.DOToGraph.clicked.connect(self.displaypHGraph)
self.tempLabel = QLabel('<span style="color:blue"><b>Temperature:</b></span>',self)
font = self.tempLabel.font()
font.setPointSize(22)
self.tempLabel.setFont(font)
self.tempLabel.setGeometry(QtCore.QRect(10,265,190,100))
self.currentTemp = QLabel('<b>' + str(currentTemp) + '\u2103', self)
font = self.currentTemp.font()
font.setPointSize(22)
self.currentTemp.setFont(font)
self.currentTemp.setGeometry(QtCore.QRect(195,265,150,100))
self.currentStatus = QLabel('<b><u>Other Parameters</u><b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 325, 200, 50))
self.currentStatus = QLabel('Current Cycle: ' + '<b>' + currentState + '</b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 340, 200, 50))
self.currentCycleTime = QLabel('Current Cycle Time (HH:MM:SS): ' + '<b>' + currentCycTime + '</b>', self)
font = self.currentCycleTime.font()
font.setPointSize(10)
self.currentCycleTime.setFont(font)
self.currentCycleTime.setGeometry(QtCore.QRect(10, 355, 250, 50))
self.remaningCycleTime = QLabel('Remaning Cycle Time (HH:MM:SS): ' + '<b>' + remaningCycTime + '</b>', self)
font = self.remaningCycleTime.font()
font.setPointSize(10)
self.remaningCycleTime.setFont(font)
self.remaningCycleTime.setGeometry(QtCore.QRect(10, 370, 275, 50))
self.show()
# just a dummy graph that I got off a tutorial, it works for what
# i need it to do for now
def displaypHGraph(self):
print("Display pH")
self.m = LinePlot(self, width = 16, height = 9)
self.m.setGeometry(QtCore.QRect(300,40,660,370))
self.m.show()
def displayDOGraph(self):
pass
# was playing with how to update labels here. Just a counter
# that counts up the value from the initial
# this will eventually be replaced with sensor inputs
def updatepH(self):
global current_pH
global lower_pH
global upper_pH
current_pH = current_pH + 0.01
display_pH = '{0:0.2f}'.format(current_pH)
if current_pH < lower_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
elif current_pH > upper_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
else:
self.currentpH.setText('<span style="color:black"><b>' + str(display_pH) + '<b></span>')
# same thing as with the updatepH function except for DO
def updateDO(self):
global current_DO
global lower_DO
current_DO = current_DO + 0.01
display_DO = '{0:0.2f}'.format(current_DO)
if current_DO < lower_DO:
self.currentDO.setText('<span style = "color:red"><b>' + str(display_DO) + ' mg/L</b></span>')
else:
self.currentDO.setText('<span style = "color:black"><b>' + str(display_DO)+ ' mg/L</b></span>')
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
# dummy plot, was learning how to put a matplotlib
# it works for now
class LinePlot(FigureCanvas):
def __init__(self, parent=None, width=16, height=9, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
data = [6.89,6.90,6.91,6.92,6.93,6.92,6.96,6.99,7.12,7.14,6.98,6.93,7.01,6.90,7.11,7.21,7.13,6.99]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('pH')
ax.set_xlabel('Time')
ax.set_ylabel('pH Value')
self.draw()
def main():
app = QApplication(sys.argv)
ex = drawMenuBar()
timer = QTimer()
timer.timeout.connect(ex.updatepH)
timer.timeout.connect(ex.updateDO)
timer.start(1000)
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
so all of this works, except the only way I can get the label to update is to close out of the setpoints popup and reopen it. What is a good way to update it upon exiting of the popup window?
Thanks.
So I'm making a music player and I want a section where can see my songs, Page by page. The page switching works but the text doesn't update. I've tried googleing but i coudn't find a fitting/working anwser. For the people that want it, this is what my idle says:
1
0
2
3
n1
n2
1
1
2
3
Anyway here is my code:
import sys
import os
import pygame
from PyQt4 import QtGui, QtCore
from time import sleep
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle("Music Player Alpha")
AutoPlay = True
Song = os.listdir('/home/pi/Desktop/Muziek/' )
Song = sorted(Song)
self.Song = Song
self.CurrentSong = 0
self.PageNum = 0
pygame.mixer.init()
pygame.mixer.music.load('/home/pi/Desktop/Muziek/' + Song[0])
pygame.mixer.music.play()
self.home()
def home(self):
print("1")
print(self.PageNum)
btnQuit = QtGui.QPushButton("Quit", self)
btnQuit.clicked.connect(self.close)
btnQuit.move(400,270)
btnPlay = QtGui.QPushButton("Play", self)
btnPlay.clicked.connect(self.play)
btnPlay.move(100, 270)
btnPause = QtGui.QPushButton("Pause", self)
btnPause.clicked.connect(self.pause)
btnPause.move(200, 270)
btnNext = QtGui.QPushButton("Next", self)
btnNext.clicked.connect(self.next)
btnNext.move(300, 270)
btnPrevious = QtGui.QPushButton("Previous", self)
btnPrevious.clicked.connect(self.previous)
btnPrevious.move(0, 270)
btnPrevPage = QtGui.QPushButton("Prev Page", self)
btnPrevPage.clicked.connect(self.PrevPage)
btnPrevPage.move(0,160)
btnNextPage = QtGui.QPushButton("Next Page", self)
btnNextPage.clicked.connect(self.NextPage)
btnNextPage.move(100, 160)
try:
txtNum1 = QtGui.QLabel(self.Song[0 + 10*self.PageNum], self)
txtNum1.resize(500, 30)
txtNum2 = QtGui.QLabel(self.Song[1 + 10*self.PageNum], self)
txtNum2.move(0, 15)
txtNum2.resize(500, 30)
txtNum3 = QtGui.QLabel(self.Song[2 + 10*self.PageNum], self)
txtNum3.move(0, 30)
txtNum3.resize(500, 30)
txtNum4 = QtGui.QLabel(self.Song[3 + 10*self.PageNum], self)
txtNum4.move(0, 45)
txtNum4.resize(500, 30)
txtNum5 = QtGui.QLabel(self.Song[4 + 10*self.PageNum], self)
txtNum5.move(0, 60)
txtNum5.resize(500, 30)
txtNum6 = QtGui.QLabel(self.Song[5 + 10*self.PageNum], self)
txtNum6.move(0, 75)
txtNum6.resize(500, 30)
txtNum7 = QtGui.QLabel(self.Song[6 + 10*self.PageNum], self)
txtNum7.move(0, 90)
txtNum7.resize(500, 30)
txtNum8 = QtGui.QLabel(self.Song[7 + 10*self.PageNum], self)
txtNum8.move(0, 105)
txtNum8.resize(500, 30)
txtNum9 = QtGui.QLabel(self.Song[8 + 10*self.PageNum], self)
txtNum9.move(0, 120)
txtNum9.resize(500, 30)
txtNum10 = QtGui.QLabel(self.Song[9 + 10*self.PageNum], self)
txtNum10.move(0, 135)
txtNum10.resize(500, 30)
print("2")
except IndexError:
print("2.5")
self.show()
print("3")
def close(self):
sys.exit()
def play(self):
pygame.mixer.music.unpause()
def pause(self):
pygame.mixer.music.pause()
def next(self, event):
self.CurrentSong = self.CurrentSong + 1
if self.CurrentSong > len(self.Song) + 1:
self.CurrentSong = 0
pygame.mixer.music.load('/home/pi/Desktop/Muziek/' + self.Song[self.CurrentSong])
pygame.mixer.music.play()
return self.CurrentSong;
def previous(self, event):
self.CurrentSong = self.CurrentSong - 1
if self.CurrentSong < 0:
self.CurrentSong = len(self.Song) -1
pygame.mixer.music.load('/home/pi/Desktop/Muziek/' + self.Song[self.CurrentSong])
pygame.mixer.music.play()
def PrevPage(self, event):
print("p1")
self.PageNum = self.PageNum - 1
if self.PageNum < 0 :
print("p<0")
self.PageNum = 0
print("p2")
self.home()
return self.PageNum;
def NextPage(self, event):
print("n1")
self.PageNum = self.PageNum + 1
if self.PageNum > len(self.Song) / 10:
print("n>0")
self.PageNum = self.PageNum - 1
print("n2")
self.home()
return self.PageNum;
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
The problem is that every time you call the home() function you are creating new labels, what you have to do is just update the text, for this we create a list of labels. Avoid using try and except since the program may have errors, it is better to verify that the index of the list is in the range.
When closing the window it is better to release the sound resource with pygame.mixer.quit() before closing the window, for this it is better to overwrite closeEvent().
import sys
import os
import pygame
from PyQt4 import QtGui, QtCore
from time import sleep
class Window(QtGui.QMainWindow):
song_per_page = 10
directory = '/home/pi/Desktop/Muziek/'
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle("Music Player Alpha")
AutoPlay = True
Song = os.listdir(self.directory)
Song = sorted(Song)
self.Song = Song
self.CurrentSong = 0
self.PageNum = 0
pygame.mixer.init()
self.txtNums = []
self.home()
self.song()
def home(self):
btnQuit = QtGui.QPushButton("Quit", self)
btnQuit.clicked.connect(self.close)
btnQuit.move(400, 270)
btnPlay = QtGui.QPushButton("Play", self)
btnPlay.clicked.connect(self.play)
btnPlay.move(100, 270)
btnPause = QtGui.QPushButton("Pause", self)
btnPause.clicked.connect(self.pause)
btnPause.move(200, 270)
btnNext = QtGui.QPushButton("Next", self)
btnNext.clicked.connect(self.next)
btnNext.move(300, 270)
btnPrevious = QtGui.QPushButton("Previous", self)
btnPrevious.clicked.connect(self.previous)
btnPrevious.move(0, 270)
btnPrevPage = QtGui.QPushButton("Prev Page", self)
btnPrevPage.clicked.connect(self.PrevPage)
btnPrevPage.move(0, 160)
btnNextPage = QtGui.QPushButton("Next Page", self)
btnNextPage.clicked.connect(self.NextPage)
btnNextPage.move(100, 160)
for i in range(self.song_per_page):
txtNum = QtGui.QLabel(self)
txtNum.resize(500, 30)
txtNum.move(0, 15 * i)
self.txtNums.append(txtNum)
self.updateLabels()
self.show()
def updateLabels(self):
print(self.CurrentSong, self.PageNum)
for i in range(len(self.txtNums)):
index = i + self.song_per_page * self.PageNum
self.txtNums[i].clear()
if index < len(self.Song):
self.txtNums[i].setText(self.Song[i + self.song_per_page * self.PageNum])
def closeEvent(self, event):
pygame.mixer.quit()
QtGui.QMainWindow.closeEvent(self, event)
def play(self):
pygame.mixer.music.unpause()
def pause(self):
pygame.mixer.music.pause()
def song(self):
try:
pygame.mixer.music.load(self.directory + self.Song[self.CurrentSong])
pygame.mixer.music.play()
except pygame.error:
print("Module format not recognized")
self.updateLabels()
def next(self, event):
self.CurrentSong = (self.CurrentSong + 1) % len(self.Song)
self.song()
def previous(self, event):
self.CurrentSong = (self.CurrentSong - 1) % len(self.Song)
self.song()
def PrevPage(self, event):
self.PageNum = self.PageNum - 1
if self.PageNum < 0:
self.PageNum = 0
self.updateLabels()
def NextPage(self, event):
if self.song_per_page * (self.PageNum + 1) - 1 < len(self.Song):
self.PageNum = self.PageNum + 1
self.updateLabels()
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
I have a simple python QT multiplication program. There are 3 fields, first random number(read only), second random number(read only) and third line edit for user to input result. If first * second = result then show Right Label, else show Wrong Label. I would like to replace exit button with play again button, so when the user press it, to regenerate random numbers and clear all result labels and user try again.
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(650, 644)
self.label_71 = QtGui.QLabel(Form)
self.label_71.setGeometry(QtCore.QRect(70, 20, 481, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(26)
self.label_71.setFont(font)
self.label_71.setObjectName(_fromUtf8("label_71"))
self.layoutWidget = QtGui.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(200, 570, 221, 29))
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.horizontalLayout_51 = QtGui.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_51.setMargin(0)
self.horizontalLayout_51.setObjectName(_fromUtf8("horizontalLayout_51"))
self.pushButton_2 = QtGui.QPushButton(self.layoutWidget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_2.clicked.connect(self.exit_)
self.horizontalLayout_51.addWidget(self.pushButton_2)
self.pushButton = QtGui.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.praxis)
self.horizontalLayout_51.addWidget(self.pushButton)
### Line Edit 1 - 2 ###
self.count = 124
self.list_x1 = []
self.list_y1 = []
for i in range(10):
self.x1 = randint(2,9)
self.list_x1.append(self.x1)
self.ln1 = "self.lineEdit1_" + str(i)
self.ln1 = QtGui.QLineEdit(Form)
self.ln1.setText(str(self.x1))
self.ln1.setReadOnly(True)
self.ln1.setGeometry(QtCore.QRect(74, self.count, 40, 26))
self.ln1.setAlignment(QtCore.Qt.AlignCenter)
self.ln1.setObjectName(_fromUtf8("lineEdit"))
self.y1 = randint(2,9)
self.list_y1.append(self.y1)
self.ln2 = "self.lineEdit2_" + str(i)
self.ln2 = QtGui.QLineEdit(Form)
self.ln2.setText(str(self.y1))
self.ln2.setReadOnly(True)
self.ln2.setGeometry(QtCore.QRect(140, self.count, 40, 26))
self.ln2.setAlignment(QtCore.Qt.AlignCenter)
self.ln2.setObjectName(_fromUtf8("lineEdit_2"))
self.count += 35
#Εισαγωγή 1ης στήλης
self.count = 124
self.ln3_value = []
for i in range(10):
self.ln3 = "self.lineEdit3_" + str(i)
self.ln3_value.append(self.ln3)
self.ln3_value[i] = QtGui.QLineEdit(Form)
self.ln3_value[i].setGeometry(QtCore.QRect(206, self.count, 40, 26))
self.ln3_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln3_value[i].setObjectName(_fromUtf8("lineEdit_3"))
self.count += 35
### Line Edit 3- 4 ###
self.count = 124
self.list_x2 = []
self.list_y2 = []
for i in range(10):
self.x2 = randint(2,9)
self.list_x2.append(self.x2)
self.ln4 = "self.lineEdit4_" + str(i)
self.ln4 = QtGui.QLineEdit(Form)
self.ln4.setText(str(self.x2))
self.ln4.setReadOnly(True)
self.ln4.setGeometry(QtCore.QRect(348, self.count, 40, 26))
self.ln4.setAlignment(QtCore.Qt.AlignCenter)
self.ln4.setObjectName(_fromUtf8("lineEdit_4"))
self.y2 = randint(2,9)
self.list_y2.append(self.y2)
self.ln5 = "self.lineEdit5_" + str(i)
self.ln5 = QtGui.QLineEdit(Form)
self.ln5.setText(str(self.y2))
self.ln5.setReadOnly(True)
self.ln5.setGeometry(QtCore.QRect(414, self.count, 40, 26))
self.ln5.setAlignment(QtCore.Qt.AlignCenter)
self.ln5.setObjectName(_fromUtf8("lineEdit_5"))
self.count += 35
#Εισαγωγή 2ης στήλης
self.count = 124
self.ln6_value = []
for i in range(10):
self.ln6 = "self.lineEdit5_" + str(i)
self.ln6_value.append(self.ln3)
self.ln6_value[i] = QtGui.QLineEdit(Form)
self.ln6_value[i].setGeometry(QtCore.QRect(480, self.count, 40, 26))
self.ln6_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln6_value[i].setObjectName(_fromUtf8("lineEdit_6"))
self.count += 35
### / Line Edit 1 - 4 ###
### Labels 1 - 6 ###
self.lbl1_count = 119
for i in range(10):
self.lbl_1 = "self.label1_" + str(i)
self.lbl_1 = QtGui.QLabel(Form)
self.lbl_1.setGeometry(QtCore.QRect(120, self.lbl1_count, 14, 34))
self.lbl_1.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_1.setFont(font)
self.lbl_1.setObjectName(_fromUtf8("label"))
self.lbl1_count += 35
self.lbl2_count = 119
for i in range(10):
self.lbl_2 = "self.label2_" + str(i)
self.lbl_2 = QtGui.QLabel(Form)
self.lbl_2.setGeometry(QtCore.QRect(186, self.lbl2_count, 14, 34))
self.lbl_2.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_2.setFont(font)
self.lbl_2.setObjectName(_fromUtf8("label_2"))
self.lbl2_count += 35
self.lbl3_list = []
self.lbl3_count = 119
for i in range(10):
self.lbl_3 = "self.label3_" + str(i)
self.lbl3_list.append(self.lbl_3)
self.lbl3_list[i] = QtGui.QLabel(Form)
self.lbl3_list[i].setGeometry(QtCore.QRect(252, self.lbl3_count, 80, 34))
self.lbl3_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl3_list[i].setFont(font)
self.lbl3_list[i].setObjectName(_fromUtf8("label_3"))
self.lbl3_count += 35
self.lbl4_count = 119
for i in range(10):
self.lbl_4 = "self.label2_" + str(i)
self.lbl_4 = QtGui.QLabel(Form)
self.lbl_4.setGeometry(QtCore.QRect(394, self.lbl4_count, 14, 34))
self.lbl_4.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_4.setFont(font)
self.lbl_4.setObjectName(_fromUtf8("label_2"))
self.lbl4_count += 35
self.lbl5_count = 119
for i in range(10):
self.lbl_5 = "self.label5_" + str(i)
self.lbl_5 = QtGui.QLabel(Form)
self.lbl_5.setGeometry(QtCore.QRect(460, self.lbl5_count, 14, 34))
self.lbl_5.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_5.setFont(font)
self.lbl_5.setObjectName(_fromUtf8("label_5"))
self.lbl5_count += 35
self.lbl6_list = []
self.lbl6_count = 119
for i in range(10):
self.lbl_6 = "self.label6_" + str(i)
self.lbl6_list.append(self.lbl_6)
self.lbl6_list[i] = QtGui.QLabel(Form)
self.lbl6_list[i].setGeometry(QtCore.QRect(526, self.lbl6_count, 80, 34))
self.lbl6_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl6_list[i].setFont(font)
self.lbl6_list[i].setObjectName(_fromUtf8("label_6"))
self.lbl6_count += 35
### / Labels 1 - 6 ###
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Multiplication", None))
self.label_71.setText(_translate("Form", "Multiplication", None))
self.pushButton_2.setText(_translate("Form", "Exit", None))
self.pushButton.setText(_translate("Form", "Check", None))
def praxis(self):
self.lbl3_count = 119
for i in range(10):
self.val = self.ln3_value[i]
self.val2 = self.ln6_value[i]
self.get_val = self.val.text()
self.get_val2 = self.val2.text()
self.get_val_str = str(self.get_val)
self.get_val2_str = str(self.get_val2)
self.summary = self.list_y1[i] * self.list_x1[i]
self.summary2 = self.list_y2[i] * self.list_x2[i]
self.summary_int = str(self.summary)
self.summary_int2 = str(self.summary2)
if self.summary_int == self.get_val_str:
self.lbl3_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl3_list[i].setStyleSheet('color: green')
else:
self.lbl3_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl3_list[i].setStyleSheet('color: red')
if self.summary_int2 == self.get_val2_str:
self.lbl6_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl6_list[i].setStyleSheet('color: green')
else:
self.lbl6_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl6_list[i].setStyleSheet('color: red')
def exit_(self):
import sys
sys.exit()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())