class Ui_Dialog(object): def openWindow(self): id = login(self.lineEdit.text(), self.lineEdit_2.text()) if id is not None: self.window = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.window) MainWindow.hide() self.window.show() def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 300) Dialog.setMinimumSize(QtCore.QSize(400, 300)) Dialog.setMaximumSize(QtCore.QSize(400, 300)) self.textBrowser = QtWidgets.QTextBrowser(Dialog) self.textBrowser.setGeometry(QtCore.QRect(10, 20, 380, 80)) self.textBrowser.setObjectName("textBrowser") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(20, 110, 50, 15)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(30, 140, 60, 20)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setGeometry(QtCore.QRect(30, 200, 60, 15)) self.label_3.setObjectName("label_3") self.lineEdit = QtWidgets.QLineEdit(Dialog) self.lineEdit.setGeometry(QtCore.QRect(90, 140, 290, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(Dialog) self.lineEdit_2.setGeometry(QtCore.QRect(90, 200, 290, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(310, 250, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.openWindow) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.textBrowser.setHtml( _translate( "Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:48pt; font-weight:600; color:#aa0000;\">Jaque</span><span style=\" font-size:48pt; font-weight:600; color:#a6a6a6;\">Bank</span></p></body></html>" )) self.label.setText(_translate("Dialog", "Log-In:")) self.label_2.setText(_translate("Dialog", "Username:"******"Dialog", "Password:"******"Dialog", "Log-In"))
class MyForm(QMainWindow): def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.run_button = self.ui.run_button self.entropy_line = self.ui.entropy_line self.entropy_line_2 = self.ui.entropy_line_2 self.entropy_line_3 = self.ui.entropy_line_3 self.class_spinbox = self.ui.class_spinbox self.entropy_line_2.setText("8") self.entropy_line_3.setText("8") self.entropia = entropy self.max_entropy_value() self.class_spinbox.valueChanged.connect(self.max_entropy_changed) self.run_button.clicked.connect(self.run) def run(self): self.ent = self.entropy_line.text() self.class_num = self.class_spinbox.value() self.x = self.entropy_line_2.text() self.y = self.entropy_line_3.text() self.error_dialog = self.ui.error_dialog try: self.entropia.entropy(self, self.class_num, self.x, self.y, self.ent) except: self.error_dialog.showMessage("Zbyt duża wartość.") def max_entropy_value(self): self.x = self.entropy_line_2.text() self.y = self.entropy_line_3.text() self.class_num = self.class_spinbox.value() self.max = self.entropia.max_entropy(self, self.class_num, self.x, self.y) text = "Maksymalna entropia: " + str(self.max) self.entropy_line.setPlaceholderText(text) def max_entropy_changed(self): self.x = self.entropy_line_2.text() self.y = self.entropy_line_3.text() self.class_num = self.class_spinbox.value() try: self.max = self.entropia.max_entropy(self, self.class_num, self.x, self.y) except: self.error_dialog.showMessage("Ustaw rozmiar obrazu.") text = "Maksymalna entropia: " + str(self.max) self.entropy_line.setPlaceholderText(text)
class MyForm(QMainWindow): def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.run_button = self.ui.run_button self.entropy_line = self.ui.entropy_line self.entropy_line_2 = self.ui.entropy_line_2 self.entropy_line_3 = self.ui.entropy_line_3 self.class_spinbox = self.ui.class_spinbox self.run_button.clicked.connect(self.run) def run(self): self.ent = self.entropy_line.text() self.class_num = self.class_spinbox.value() self.x = self.entropy_line_2.text() self.y = self.entropy_line_3.text() self.entropia = entropy self.entropia.entropy(self, self.class_num, self.x, self.y, self.ent)
class mywindow(QtWidgets.QMainWindow): okyd = '0330230' # код по окуд key_no_update_lines = False def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.current_state_period = self.ui.comboBox.currentText() self.current_state_case = self.ui.comboBox_2.currentText() self.ui.CreateRow.clicked.connect(self.CreateRowClicked) self.ui.CreateButton.clicked.connect(self.CreateButtonClicked) self.ui.textEdit.textChanged.connect(self.UpdateHead) self.ui.date_create.dateTimeChanged.connect(self.UpdateHead) self.ui.comboBox.currentTextChanged.connect(self.UpdatePeriod) self.ui.comboBox_2.currentTextChanged.connect(self.UpdateCase) self.ui.tableWidget.insertRow(self.ui.tableWidget.rowCount()) self.UpdateHead() row = self.ui.tableWidget.rowCount() for i in range(13): item = QTableWidgetItem() item.setText(" ") self.ui.tableWidget.setItem(row-1, i, item) # ТАРА self.line0 = [""] # наименование self.line1 = [""] # код # ПОСТАВЩИК self.line2 = [""] # наименование self.line3 = [""] # код # ЦЕНА self.line4 = [""] # цена # НАЧАЛО ПЕРИОДА self.line5 = [""] # колво self.line6 = [""] # сумма # ПРИХОД self.line7 = [""] # колво self.line8 = [""] # сумма # РАСХОД self.line9 = [""] # колво self.line10 = [""] # сумма # КОНЕЦ ПЕРИОДА self.line11 = [""] # колво self.line12 = [""] # сумма self.ui.tableWidget.cellChanged.connect(self.TableRouteen) # обновление данных в таблицах def TableRouteen(self): if not self.key_no_update_lines: row = self.ui.tableWidget.currentRow() # ТАРА self.line0[row] = self.ui.tableWidget.item(row, 0).text() self.line1[row] = self.ui.tableWidget.item(row, 1).text() # ПОСТАВЩИК self.line2[row] = self.ui.tableWidget.item(row, 2).text() self.line3[row] = self.ui.tableWidget.item(row, 3).text() # ЦЕНА self.line4[row] = self.ui.tableWidget.item(row, 4).text() if self.current_state_period == "Начало периода": # НАЧАЛО ПЕРИОДА self.line5[row] = self.ui.tableWidget.item(row, 5).text() self.line6[row] = self.ui.tableWidget.item(row, 6).text() if self.current_state_period == "Конец периода": # КОНЕЦ ПЕРИОДА self.line11[row] = self.ui.tableWidget.item(row, 5).text() self.line12[row] = self.ui.tableWidget.item(row, 6).text() if self.current_state_case == "Приход": # ПРИХОД self.line7[row] = self.ui.tableWidget.item(row, 7).text() self.line8[row] = self.ui.tableWidget.item(row, 8).text() if self.current_state_case == "Расход": # РАСХОД self.line9[row] = self.ui.tableWidget.item(row, 7).text() self.line10[row] = self.ui.tableWidget.item(row, 8).text() # таблица def TableRowAdd(self): # ТАРА self.line0.append("") self.line1.append("") # ПОСТАВЩИК self.line2.append("") self.line3.append("") # ЦЕНА self.line4.append("") # НАЧАЛО ПЕРИОДА self.line5.append("") self.line6.append("") # ПРИХОД self.line7.append("") self.line8.append("") # РАСХОД self.line9.append("") self.line10.append("") # КОНЕЦ ПЕРИОДА self.line11.append("") self.line12.append("") # обновление таблицы приход-расход def UpdateCase(self): if self.current_state_case != self.ui.comboBox_2.currentText(): self.key_no_update_lines = True if self.ui.comboBox_2.currentText() == "Приход": self.current_state_case = "Приход" self.ui.label_of_period_2.setText("Приход") for i in range(self.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(i, 7, QTableWidgetItem(self.line7[i])) self.ui.tableWidget.setItem(i, 8, QTableWidgetItem(self.line8[i])) else: self.current_state_case = "Расход" self.ui.label_of_period_2.setText("Расход") for i in range(self.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(i, 7, QTableWidgetItem(self.line9[i])) self.ui.tableWidget.setItem(i, 8, QTableWidgetItem(self.line10[i])) self.key_no_update_lines = False # обновление таблицы начало-конец периода def UpdatePeriod(self): if self.current_state_period != self.ui.comboBox.currentText(): self.key_no_update_lines = True if self.ui.comboBox.currentText() == "Начало периода": self.current_state_period = "Начало периода" self.ui.label_of_period.setText("Начало периода") for i in range(self.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(i, 5, QTableWidgetItem(self.line5[i])) self.ui.tableWidget.setItem(i, 6, QTableWidgetItem(self.line6[i])) else: self.current_state_period = "Конец периода" self.ui.label_of_period.setText("Конец периода") for i in range(self.ui.tableWidget.rowCount()): self.ui.tableWidget.setItem(i, 5, QTableWidgetItem(self.line11[i])) self.ui.tableWidget.setItem(i, 6, QTableWidgetItem(self.line12[i])) self.key_no_update_lines = False # обновление шапки def UpdateHead(self): num = self.ui.textEdit.toPlainText() from_ = self.ui.date_create.text() self.ui.label.setText('Отчет по таре: документ ' + num + ' от ' + from_) # обработчик кнопки СОЗДАТЬ def CreateButtonClicked(self): self.organization = self.ui.org_text.toPlainText() self.podrazdelenie = self.ui.podraz_text.toPlainText() self.number_doc = self.ui.textEdit.toPlainText() self.date_start = self.ui.date_begin.text() self.date_end = self.ui.date_end.text() self.date_create = self.ui.date_create.text() self.okpo = self.ui.code_text.toPlainText() self.okdp = self.ui.okdp_text.toPlainText() self.type_active = self.ui.deya_text.toPlainText() self.otv_face = self.ui.who_text.toPlainText() self.dolz = self.ui.work_text.toPlainText() self.tabel_num = self.ui.tabel_text.toPlainText() workbook = load_workbook('example.xlsx') sheet = workbook['стр1'] sheet['A6'] = self.organization sheet['A8'] = self.podrazdelenie sheet['G15'] = self.dolz + ' ' + self.otv_face sheet['AE15'] = self.tabel_num sheet['AD5'] = self.okyd sheet['AD6'] = self.okpo sheet['AD7'] = self.okpo sheet['AD9'] = self.okdp sheet['AD11'] = self.type_active sheet['P14'] = self.number_doc sheet['U14'] = self.date_create[:-5] sheet['W14'] = self.date_start sheet['Y14'] = self.date_end rows = len(self.line0) for i in range(rows): if i <= 6: row = str(i + 23) sheet['A' + row] = i+1 sheet['B' + row] = self.line0[i] sheet['F' + row] = self.line1[i] sheet['H' + row] = self.line2[i] sheet['J' + row] = self.line3[i] sheet['K' + row] = self.line4[i] sheet['M' + row] = self.line5[i] sheet['P' + row] = self.line6[i] sheet['U' + row] = self.line7[i] sheet['V' + row] = self.line8[i] sheet['X' + row] = self.line9[i] sheet['Z' + row] = self.line10[i] sheet['AD' + row] = self.line11[i] sheet['AG' + row] = self.line12[i] #суммы self.line5 = [int(i) for i in self.line5] sheet['M29'] = sum(self.line5) self.line6 = [int(i) for i in self.line6] sheet['P29'] = sum(self.line6) self.line7 = [int(i) for i in self.line7] sheet['U29'] = sum(self.line7) self.line8 = [int(i) for i in self.line8] sheet['V29'] = sum(self.line8) self.line9 = [int(i) for i in self.line9] sheet['X29'] = sum(self.line9) self.line10 = [int(i) for i in self.line10] sheet['Z29'] = sum(self.line10) self.line11 = [int(i) for i in self.line11] sheet['AD29'] = sum(self.line11) self.line12 = [int(i) for i in self.line12] sheet['AG29'] = sum(self.line12) workbook.save('last.xlsx') print('saved!') # обработчик кнопки ДОБАВИТЬ ЗАПИСЬ def CreateRowClicked(self): self.key_no_update_lines = True self.ui.tableWidget.insertRow(self.ui.tableWidget.rowCount()) row = self.ui.tableWidget.rowCount() for i in range(13): item = QTableWidgetItem() item.setText(" ") self.ui.tableWidget.setItem(row-1, i, item) self.TableRowAdd() self.key_no_update_lines = False
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.saidbis = None self.ui.setupUi(self) self.ui.b1.clicked.connect(self.hello) self.show() def hello(self): th1 = threading.Thread(target=self.smart) th1.start() def smart(self): print("hello") if self.saidbis == self.ui.me.text(): self.ui.me.setText("") def speak(output): num = 0 print(output) num += 1 response = gTTS(text=output, lang='en') file = str(num) + ".mp3" response.save(file) playsound.playsound(file, True) os.remove(file) def takeCommand(): getInfo.exist() print(self.ui.me.text()) r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) said = "" try: said = r.recognize_google(audio) print(said) self.ui.me.setText(said) except Exception as e: print("e") said = False self.ui.label.setText("Sorry I didn't understand") speak("Sorry I didn't understand") return said if self.ui.me.text() == "": statement = takeCommand() else: self.saidbis = self.ui.me.text() statement = self.ui.me.text() if "good bye" in statement or "bye" in statement or "stop" in statement or "shut up" in statement: time.sleep(0.5) self.ui.label.setText( 'your personal assistant SWI is shutting down,\nGood bye!') speak('your personal assistant SWI is shutting down,Good bye!') elif "hello" in statement or "hie" in statement: tName = getInfo.read_info('name') time.sleep(0.5) self.ui.label.setText("hello " + tName + ", \nhow can i help you?") speak('hello ' + tName + ', how can i help you?') elif "me" and "know" in statement: self.ui.label.setText( "this is what i know about you. \nYour name is " + getInfo.read_info('name') + ", you have " + getInfo.read_info('age') + " years old, \nyou leave in " + getInfo.read_info('country')) speak("this is what i know about you. \nYour name is " + getInfo.read_info('name') + ", you have " + getInfo.read_info('age') + " years old, \nyou leave in " + getInfo.read_info('country')) elif 'crazy' in statement or 'f**k' in statement or "w***e" in statement or "f***" in statement: time.sleep(0.5) self.ui.label.setText("it's not nice, I'm on strike") speak("it's not nice, I'm on strike") elif 'wikipedia' in statement: time.sleep(0.5) speak('Searching Wikipedia...') self.ui.label.setText('Searching Wikipedia...') statement = statement.replace("Searching wikipedia", "") results = wikipedia.summary(statement, sentences=1) self.ui.label.setText("According to Wikipedia") speak("According to Wikipedia") self.ui.label.setText(results) speak(results) elif 'youtube' in statement: time.sleep(0.5) webbrowser.open_new_tab("https://www.youtube.com") self.ui.label.setText('youtube is open now') speak('youtube is open now.') time.sleep(5) elif 'google' in statement: time.sleep(0.5) webbrowser.open_new_tab("https://www.google.com") self.ui.label.setText("Google is open now.") speak("Google is open now.") time.sleep(5) elif 'gmail' in statement: time.sleep(0.5) webbrowser.open_new_tab("gmail.com") self.ui.label.setText("Google Mail open now") speak("Google Mail open now") time.sleep(5) elif 'what' and 'like' in statement: time.sleep(0.5) self.ui.label.setText("I like help you") speak("I like help you") time.sleep(5) elif "weather" in statement: time.sleep(0.5) api_key = "64f7f61815d3b00e86678284fcc41ff7" base_url = "https://api.openweathermap.org/data/2.5/weather?" self.ui.label.setText("whats the city name?") speak("whats the city name.") city_name = takeCommand() complete_url = base_url + "appid=" + api_key + "&q=" + city_name response = requests.get(complete_url) x = response.json() if x["cod"] != "404": y = x["main"] current_temperature = y["temp"] current_humidiy = y["humidity"] z = x["weather"] weather_description = z[0]["description"] self.ui.label.setText(" Temperature in kelvin unit is: " + str(current_temperature) + "\n humidity is: " + str(current_humidiy) + "%" + "\n description: " + str(weather_description)) self.ui.label.adjustSize() speak(" Temperature in kelvin unit is. " + str(current_temperature) + "\n .humidity is. " + str(current_humidiy) + "percent" + "\n .description. " + str(weather_description)) else: self.ui.label.setText(" City Not Found in the database") speak(" City Not Found in the database") elif 'time' in statement: time.sleep(0.5) strTime = datetime.datetime.now().strftime("%H:%M:%S") self.ui.label.setText(f"the time is {strTime}") speak(f"the time is {strTime}") elif 'who' and 'you' in statement or 'what' and 'do' in statement: time.sleep(0.5) self.ui.label.setText( 'I am SW1 version 1.2 your persoanl assistant. \nI am programmed to meet your needs' ) speak( 'I am SW1 version 1 point 2 your persoanl assistant. I am programmed to meet your needs' ) elif "made you" in statement or "created you" in statement or "discovered you" in statement: time.sleep(0.5) self.ui.label.setText("I was built by vultorio") speak("I was built by vultorio") elif "stackoverflow" in statement: time.sleep(0.5) webbrowser.open_new_tab("https://stackoverflow.com/login") self.ui.label.setText("Here is stackoverflow") speak("Here is stackoverflow") elif 'news' in statement: time.sleep(0.5) news = webbrowser.open_new_tab("https://www.bfmtv.com/") self.ui.label.setText( 'Here are some headlines from the bfmtv sites.') speak('Here are some headlines from the bfmtv sites.') time.sleep(6) # elif 'search' in statement: # statement = statement.replace("search", "") # webbrowser.open_new_tab(statement) # time.sleep(5) elif 'ask' in statement: time.sleep(0.5) self.ui.label.setText( 'I can answer to computational and geographical \nquestions and what question do you want to ask now' ) speak( 'I can answer to computational and geographical questions and \nwhat question do you want to ask now' ) question = takeCommand() app_id = "R2K75H-7ELALHR35X" client = wolframalpha.Client('R2K75H-7ELALHR35X') res = client.query(question) answer = next(res.results).text self.ui.label.setText(answer) speak(answer) elif "log off" in statement or "lof off on off" in statement: time.sleep(0.5) self.ui.label.setText( "Ok , your pc will log off in 10 sec make \nsure you exit from all applications" ) speak( "Ok , your pc will log off in 10 sec make \nsure you exit from all applications" ) subprocess.call(["shutdown", "/l"]) elif "turn on" in statement: if "strip" in statement: time.sleep(0.5) x = requests.get('http://192.168.1.66/control?cmd=gpio,0,0') self.ui.label.setText("strip led is turn on.") speak("strip led is turn on.") if "back" in statement: time.sleep(0.5) x = requests.get('http://192.168.1.66/control?cmd=gpio,0,1') self.ui.label.setText("strip led is turn on.") speak("strip led is turn on.") elif "turn off" in statement: if "strip" in statement: time.sleep(0.5) x = requests.get('http://192.168.1.66/control?cmd=gpio,13,0') self.ui.label.setText("strip led is turn off.") speak("strip led is turn off.") if "back" in statement: time.sleep(0.5) x = requests.get('http://192.168.1.66/control?cmd=gpio,13,1') self.ui.label.setText("strip led is turn off.") speak("strip led is turn off.") elif "do you like banana" in statement or "do you like bananas" in statement: time.sleep(0.5) webbrowser.open_new_tab( "https://www.youtube.com/watch?v=ef-P_sC-_0c&ab_channel=JenNard" ) self.ui.label.setText("I think that expresses my answer") speak("I think that expresses my answer") elif "definition of" in statement: time.sleep(0.5) statement = statement.replace("definition of", "") results = wikipedia.summary(statement, sentences=1) self.ui.label.setText(results) speak(results) elif "what" in statement: self.ui.label.setText("what, what") speak("what? what.") elif "translate" in statement or "what's mean" in statement: if "in" in statement: if "in french" in statement: language = "french" if "in german" in statement: language = "german" if "in spanish" in statement: language = "spanish" print("hello") statement = statement.replace("translate", "") statement = statement.replace("what's mean", "") statement = statement.replace("in german", "") statement = statement.replace("in french", "") statement = statement.replace("in spanish", "") print(statement) translator = Translator(from_lang="english", to_lang=language) translation = translator.translate(statement) print(translation) self.ui.label.setText(statement + " in " + language + " mean with \nmy english accent " + translation) speak(statement + " in " + language + " mean with my english accent " + translation) else: statement = statement.replace("translate", "") statement = statement.replace("what's mean", "") print(statement) self.ui.label.setText( "in witch languge do you want to translate?") speak("in witch languge do you want to translate?") statement = takeCommand().lower() language = statement translator = Translator(from_lang="english", to_lang=statement) translation = translator.translate(statement) print(translation) self.ui.label.setText(statement + " in " + language + " mean with \nmy english accent " + translation) speak(statement + " in " + language + " mean with my english accent " + translation) else: if statement != "False": time.sleep(0.5) webbrowser.open_new_tab(statement) self.ui.label.setText( "here is what I found on the web for:\n" + statement) speak("here is what I found on the web for: " + statement) def resizeMainWindow(self, width, height): # CREATE ANIMATION self.animation = QPropertyAnimation(self, b"size") self.animation.setDuration(1000) self.animation.setEndValue(QtCore.QSize(width, height)) self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuad) self.animation.start()
class Test(QMainWindow): def __init__(self, parent=None): super(Test, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.save) self.ui.pushButton_2.clicked.connect(self.before) self.ui.pushButton_3.clicked.connect(self.after) self.ui.pushButton_4.clicked.connect(self.calib) self.ui.verticalSlider.valueChanged['int'].connect(self.value_change) self.ui.verticalSlider_2.valueChanged['int'].connect( self.value_change_2) self.ui.verticalSlider_3.valueChanged['int'].connect( self.value_change_3) self.b = 0 self.g = 0 self.r = 0 self.img_name = 1 self.load_img(str(self.img_name), 0, 0, 0) # self.ui. def save(self, file_name): self.load_img(str(self.img_name), 1, 1, 0) def before(self): if self.img_name > 1: self.img_name -= 1 self.load_img(str(self.img_name), 0, 0, 0) def after(self): self.img_name += 1 self.load_img(str(self.img_name), 0, 0, 0) def calib(self): self.load_img(str(self.img_name), 1, 0, 1) def value_change(self): # self.verticalSlider.value() self.ui.lcdNumber.display(self.ui.verticalSlider.value()) self.b = self.ui.verticalSlider.value() self.load_img(str(self.img_name), 1, 0, 0) def value_change_2(self): # self.verticalSlider.value() self.ui.lcdNumber_2.display(self.ui.verticalSlider_2.value()) self.g = self.ui.verticalSlider_2.value() self.load_img(str(self.img_name), 1, 0, 0) def value_change_3(self): # self.verticalSlider.value() self.ui.lcdNumber_3.display(self.ui.verticalSlider_3.value()) self.r = self.ui.verticalSlider_3.value() self.load_img(str(self.img_name), 1, 0, 0) def load_img(self, file_name, binary_flag, save_flag, calib_flag): # print ("data/" , file_name , ".jpg") self.img = cv2.imread("data/" + file_name + ".jpg", cv2.IMREAD_COLOR) img = np.copy(self.img) # img = np.float32(img) if binary_flag == 1: orgHeight, orgWidth = img.shape[:2] for i in range(orgHeight): for j in range(orgWidth): b = img[i][j][0] g = img[i][j][1] r = self.img[i][j][2] if b > self.b and g > self.g and r > self.r: img[i][j][0] = 0 img[i][j][1] = 0 img[i][j][2] = 0 if save_flag == 1: cv2.imwrite("data2/" + file_name + ".jpg", img) if calib_flag == 1: ret2, circles = cv2.findCirclesGrid( img, (10, 5), flags=cv2.CALIB_CB_SYMMETRIC_GRID) if ret2 == True: cv2.drawChessboardCorners(img, (10, 5), circles, ret2) show_img = cv2.resize(img, (480, 270)) self.drawing(show_img) def drawing(self, in_img): qimg = QImage(in_img, in_img.shape[1], in_img.shape[0], QImage.Format_RGB888) # self.uic.imageLabel.setWindowOpacity(0.8) self.ui.textBrowser.setPixmap(QPixmap.fromImage(qimg))
class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.presets = { "<Select>": { "nZeroUnit": "", "halfLife": 0.0, "timeScale": "Years" }, "Carbon-14": { "nZeroUnit": "Nuclei", "halfLife": 5730.0, "timeScale": "Years" }, "Plutonium-239": { "nZeroUnit": "Nuclei", "halfLife": 24110.0, "timeScale": "Years" }, } for preset_name in self.presets: self.ui.inputPresetsComboBox.addItem(preset_name) self.nZeroUnit = self.ui.inputNZeroLineEdit.text() self.ui.statsYAxisLabelStat.setText("0") self.ui.statsXAxisLabelStat.setText("0") self.ui.statsRealTimeStat.setText("0") self.ui.statsSimulatedTimeStat.setText("0") self.visWidth = self.ui.labelVis.width() self.visHeight = self.ui.labelVis.height() self.ui.labelVis.setPixmap(QtGui.QPixmap(self.visWidth, self.visHeight)) self.clear_canvas() pen = pg.mkPen(color='#000000') self.ui.graphWidgetHalfLifeDashboard.setBackground('w') self.ui.graphWidgetHalfLife.setBackground('w') self.graphDataDash = self.ui.graphWidgetHalfLifeDashboard.plot([0], [0], pen=pen) self.graphData = self.ui.graphWidgetHalfLife.plot([0], [0], pen=pen) self.ui.inputPresetsComboBox.currentIndexChanged[str].connect( self.apply_preset) self.ui.inputPresetsComboBox.setCurrentIndex(0) self.ui.inputNZeroLineEdit.textChanged.connect( self.change_nZero_unit_label) self.ui.inputTimeScaleComboBox.currentIndexChanged[str].connect( self.change_time_unit_label) self.ui.inputTimeScaleComboBox.setCurrentIndex(4) self.ui.controlsStartStopButton.clicked.connect(self.start_sim) self.ui.controlsResetButton.clicked.connect(self.reset_all) self.ui.controlsSimSpeedButton_1.clicked.connect( lambda: self.set_sim_speed(self.sim.defaultInterval * 4)) self.ui.controlsSimSpeedButton_2.clicked.connect( lambda: self.set_sim_speed(self.sim.defaultInterval * 2)) self.ui.controlsSimSpeedButton_3.clicked.connect( lambda: self.set_sim_speed(self.sim.defaultInterval)) self.ui.controlsSimSpeedButton_4.clicked.connect( lambda: self.set_sim_speed(self.sim.defaultInterval / 2)) self.ui.controlsSimSpeedButton_5.clicked.connect( lambda: self.set_sim_speed(self.sim.defaultInterval / 5)) def apply_preset(self, preset): selected_preset = self.presets[preset] self.ui.inputNZeroLineEdit.setText(selected_preset["nZeroUnit"]) self.ui.inputHalfLifeDoubleSpinBox.setValue( selected_preset["halfLife"]) self.ui.inputTimeScaleComboBox.setCurrentText( selected_preset["timeScale"]) def change_nZero_unit_label(self, nZeroUnit): self.ui.statsYAxisLabelStatUnit.setText(nZeroUnit) self.nZeroUnit = nZeroUnit def change_time_unit_label(self, timeUnit): self.ui.inputSimulatedTimeLabel.setText(f"Simulated {timeUnit}") self.ui.statsXAxisLabelStatUnit.setText(timeUnit) self.ui.statsSimulatedTimeStatUnit.setText(timeUnit) self.timeUnit = timeUnit def start_sim(self): nZero = self.ui.inputNZeroDoubleSpinBox.value() halfLife = self.ui.inputHalfLifeDoubleSpinBox.value() timeScale = float(self.ui.inputSimulatedTimeSpinBox.value() / 10) self.ui.inputNZeroLineEdit.textChanged.disconnect( self.change_nZero_unit_label) self.ui.controlsStartStopButton.clicked.disconnect(self.start_sim) self.ui.controlsStartStopButton.clicked.connect(self.stop_sim) self.ui.controlsStartStopButton.setText("Stop") self.ui.controlsStartStopButton.show() self.ui.graphWidgetHalfLifeDashboard.setTitle("Half Life Chart") self.ui.graphWidgetHalfLife.setTitle("Half Life Chart") self.ui.graphWidgetHalfLifeDashboard.setLabel('left', self.nZeroUnit) self.ui.graphWidgetHalfLife.setLabel('left', self.nZeroUnit) self.ui.graphWidgetHalfLifeDashboard.setLabel('bottom', self.timeUnit) self.ui.graphWidgetHalfLife.setLabel('bottom', self.timeUnit) self.sim = Sim(self, nZero=nZero, halfLife=halfLife, timeScale=timeScale) self.sim.start() def stop_sim(self): self.ui.controlsStartStopButton.clicked.disconnect(self.stop_sim) self.ui.controlsStartStopButton.hide() self.sim.stop() def reset_all(self): if self.sim.simulationActive == True: self.sim.stop() self.ui.controlsStartStopButton.show() self.clear_canvas() self.graphDataDash.setData([0], [0]) self.graphData.setData([0], [0]) self.ui.statsYAxisLabelStat.setText("0") self.ui.statsXAxisLabelStat.setText("0") self.ui.statsRealTimeStat.setText("0") self.ui.statsSimulatedTimeStat.setText("0") self.ui.controlsStartStopButton.clicked.connect(self.start_sim) self.ui.controlsStartStopButton.setText("Start") self.ui.inputNZeroLineEdit.textChanged.connect( self.change_nZero_unit_label) del self.sim def set_sim_speed(self, interval): self.sim.set_speed(interval=interval) def clear_canvas(self): painter = QtGui.QPainter(self.ui.labelVis.pixmap()) painter.eraseRect(0, 0, self.visWidth, self.visHeight) painter.end() self.ui.labelVis.update()
class Ui_Dialog(object): def openWindow(self): if self.lineEdit.text() is not '' and self.lineEdit_2.text() is not '': id = login(self.lineEdit.text(), self.lineEdit_2.text()) print(id) if id is not None: self.window = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.window, id[0][0]) MainWindow.hide() self.window.show() else: msg = QMessageBox() msg.setText("Wrong information") msg.setWindowTitle("JacBank") msg.setWindowIcon(QtGui.QIcon('icon.jpg')) msg.exec() print('no user and password found') else: if self.lineEdit.text() is '' and self.lineEdit_2.text() is not '': msg = QMessageBox() msg.setText("Username field is empty") msg.setWindowTitle("JacBank") msg.setWindowIcon(QtGui.QIcon('icon.jpg')) msg.exec() elif self.lineEdit_2.text() is '' and self.lineEdit.text( ) is not '': msg = QMessageBox() msg.setText("Password field is empty") msg.setWindowTitle("JacBank") msg.setWindowIcon(QtGui.QIcon('icon.jpg')) msg.exec() else: msg = QMessageBox() msg.setText("Password and Username fields are empty") msg.setWindowTitle("JacBank") msg.setWindowIcon(QtGui.QIcon('icon.jpg')) msg.exec() def opensignup(self): self.window = QtWidgets.QDialog() self.ui = Ui_Dialog5() self.ui.setupUi(self.window) self.window.show() def forgot_my_password(self): self.window = QtWidgets.QDialog() self.ui = Ui_Dialog7() self.ui.setupUi(self.window) self.window.show() def setupUi(self, Dialog): Dialog.setObjectName("Login") Dialog.resize(400, 300) Dialog.setMinimumSize(QtCore.QSize(400, 300)) Dialog.setMaximumSize(QtCore.QSize(400, 300)) Dialog.setWindowIcon(QtGui.QIcon('icon.jpg')) self.textBrowser = QtWidgets.QTextBrowser(Dialog) self.textBrowser.setGeometry(QtCore.QRect(10, 20, 380, 90)) self.textBrowser.setObjectName("textBrowser") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(20, 120, 50, 15)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(30, 140, 60, 20)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setGeometry(QtCore.QRect(30, 200, 60, 15)) self.label_3.setObjectName("label_3") self.lineEdit = QtWidgets.QLineEdit(Dialog) self.lineEdit.setGeometry(QtCore.QRect(90, 140, 290, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(Dialog) self.lineEdit_2.setGeometry(QtCore.QRect(90, 200, 290, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password) self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(310, 250, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.openWindow) self.pushButton2 = QtWidgets.QPushButton(Dialog) self.pushButton2.setGeometry(QtCore.QRect(20, 250, 75, 23)) self.pushButton2.setObjectName("pushButton2") self.pushButton2.clicked.connect(self.opensignup) self.pushButton3 = QtWidgets.QPushButton(Dialog) self.pushButton3.setGeometry(QtCore.QRect(105, 250, 120, 23)) self.pushButton3.setObjectName("pushButton3") self.pushButton3.clicked.connect(self.forgot_my_password) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Log-In")) self.textBrowser.setHtml( _translate( "Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:50px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:48pt; font-weight:600; color:#aa0000;\">Jac</span><span style=\" font-size:48pt; font-weight:600; color:#a6a6a6;\">Bank</span></p></body></html>" )) self.label.setText(_translate("Dialog", "Log-In:")) self.label_2.setText(_translate("Dialog", "Username:"******"Dialog", "Password:"******"Dialog", "Log-In")) self.pushButton2.setText(_translate("Dialog", "Sign Up")) self.pushButton3.setText(_translate("Dialog", "Forgot my password"))
class Window(QtWidgets.QMainWindow): # Variables used across multiple functions gamesToBeAdded = [] ids_toAdd = [] dfExport = pd.DataFrame() def __init__(self): super(Window, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.about = aboutPopup(parent=self) self.popUp = infoWindow(parent=self) self.ui.searchResults.setRowCount(0) self.ui.searchResults.setColumnCount(4) self.ui.searchResults.setHorizontalHeaderLabels( ('Name', 'Year', 'UID', 'Type')) header = self.ui.searchResults.horizontalHeader() header.setSectionResizeMode(QtWidgets.QHeaderView.Stretch) #self.popUp = infoWindow() self.ui.bgg_tabs.setTabEnabled(1, False) #self.ui.bgg_tabs.setCurrentIndex(0) self.ui.bgg_tabs.setTabEnabled(2, False) #self.ui.dfPreview.setEnabled(True) self.ui.searchButton.clicked.connect(self.api_search) self.ui.searchButton.clicked.connect(self.searchIndex) self.ui.searchLine.returnPressed.connect(self.api_search) self.ui.searchLine.returnPressed.connect(self.searchIndex) self.ui.addButton.clicked.connect(self.addIDs) self.ui.addButton.clicked.connect(self.enableButton) self.ui.removeButton.clicked.connect(self.removeIDs) self.ui.dataCollectionStart.clicked.connect(self.newWindow) #self.ui.exportButton.clicked.connect(self.updateExport) self.ui.exportButton.clicked.connect(self.saveFileDialog) self.ui.searchResults.itemDoubleClicked.connect(self.addIDs) self.ui.searchResults.itemDoubleClicked.connect(self.enableButton) self.ui.selectedGamees.itemDoubleClicked.connect(self.removeIDs) #self.ui.dfPreview.itemDoubleClicked.connect(self.dfRemoveRow) self.ui.removeRow.clicked.connect(self.dfRemoveRow) self.ui.actionAbout.triggered.connect(self.showAbout) self.ui.csvImport.clicked.connect(self.openFileNameDialog) self.ui.actionOpen.triggered.connect(self.openFileNameDialog) def clearGTA(self): self.gamesToBeAdded.clear() def searchIndex(self): self.ui.bgg_tabs.setCurrentIndex(0) def showAbout(self): self.about.show() def dfRemoveRow(self): for idx in self.ui.dfPreview.selectionModel().selectedRows(): #print(idx.row()) row = int(idx.row()) #print(self.dfExport.iloc[row]) self.dfExport.drop(self.dfExport.index[row], inplace=True) self.updatePreview() def updatePreview(self): model = pandasModel(self.dfExport) self.ui.dfPreview.setModel(model) def api_search(self): answers = query(self.ui.searchLine.text(), self.ui.gameCheck.isChecked(), self.ui.expanCheck.isChecked()) self.appendData(answers) def appendData(self, info): for i in range(len(info[0])): data.append((info[0][i], info[1][i], info[2][i], info[3][i])) self.refreshData() def refreshData(self): self.ui.searchResults.setRowCount(len(data)) row = 0 for tup in data: col = 0 for item in tup: gameinfo = QTableWidgetItem(item) self.ui.searchResults.setItem(row, col, gameinfo) col += 1 row += 1 header = self.ui.searchResults.horizontalHeader() #header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) data.clear() def addIDs(self): addedGames = [] for idx in self.ui.searchResults.selectionModel().selectedRows(): if (self.ui.searchResults.item(idx.row(), 2).text() not in self.ids_toAdd): self.ids_toAdd.append( self.ui.searchResults.item(idx.row(), 2).text()) name = self.ui.searchResults.item(idx.row(), 0).text() year = self.ui.searchResults.item(idx.row(), 1).text() self.gamesToBeAdded.append("%s (%s)" % (name, year)) addedGames.append("%s (%s)" % (name, year)) else: print("%s already in list" % (self.ui.searchResults.item(idx.row(), 0).text())) for game in addedGames: self.ui.selectedGamees.insertItem(self.ui.selectedGamees.count(), game) addedGames.clear() self.ui.searchResults.selectionModel().clearSelection() def enableButton(self): self.ui.dataCollectionStart.setEnabled(True) def removeIDs(self): r_idxs = [] for idx in self.ui.selectedGamees.selectionModel().selectedRows(): gamename = self.ui.selectedGamees.item(idx.row()).text() r_idxs.append(self.gamesToBeAdded.index(gamename)) self.gamesToBeAdded.remove(gamename) for item in self.ui.selectedGamees.selectedItems(): self.ui.selectedGamees.takeItem(self.ui.selectedGamees.row(item)) for i in r_idxs: del self.ids_toAdd[i] def newWindow(self): #self.w = infoWindow() self.popUp.show() def saveFileDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog #now = datetime.now() #dt1 = now.strftime("%H:%M_%D-%M-%y") #defaultName = dt1 + "_exp" fileName, _ = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveFileName()", "", ".csv Files (*.csv)", options=options) print(fileName) if fileName: #print(fileName) #print(self.dfExport) #print(type(fileName)) if (fileName.endswith('.csv')): expName = fileName print(fileName) print(expName) else: expName = fileName + ".csv" self.dfExport.to_csv(expName, encoding='utf-8-sig', quoting=csv.QUOTE_MINIMAL, index=False) else: print('nothing') def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog #fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",".csv Files (*.csv)", options = options) #if fileName: # print(fileName) fileURL, _ = QFileDialog.getOpenFileUrl(self, "QFileDialog.getOpenFileUrl()", "", ".csv Files (*.csv)", options=options) print(fileURL) if (fileURL.toString() != ''): self.dfExport = pd.read_csv(fileURL.toString(), index_col=False) self.ui.bgg_tabs.setTabEnabled(1, True) self.ui.bgg_tabs.setCurrentIndex(1) self.ui.dfPreview.setEnabled(True) self.updatePreview() else: print('nada')
class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): super(ApplicationWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # self.ui.btn_Game.hide() # self.ui.btn_Sendfile.hide() # self.ui.btn_Startstreaming.hide() self.ui.lbl_1.mouseReleaseEvent = self.showText1 self.ui.lbl_2.mouseReleaseEvent = self.showText2 self.ui.lbl_3.mouseReleaseEvent = self.showText3 self.ui.lbl_4.mouseReleaseEvent = self.showText4 self.ui.lbl_5.mouseReleaseEvent = self.showText5 self.ui.lbl_6.mouseReleaseEvent = self.showText6 self.ui.lbl_7.mouseReleaseEvent = self.showText7 self.ui.lbl_8.mouseReleaseEvent = self.showText8 self.ui.lbl_9.mouseReleaseEvent = self.showText9 self.current = 'X' self.numOfClicks = 0 self.isWiner = 0 self.winer = '' self.host = "10.0.0.2" self.ui.ln_IP.setText(str(self.host)) # self.text_name.setPlaceholderText('Enter your name') self.ui.btn_Gamestart.clicked.connect(self.StartGameConnection) self.ui.pushButton.clicked.connect(self.EndGameConnection) self.ui.pushButton_2.clicked.connect(self.ReturnBack) # self.ui.btn_Startchat.clicked.connect(self.Statchat) self.ui.btn_Endstreaming.clicked.connect(self.recieveStream) self.ui.btn_Streaming.clicked.connect(self.GoToStreamingWidget) self.ui.btn_Startstreaming.clicked.connect(self.SendStream) self.ui.btn_Back.clicked.connect(self.ReturnBack) self.ui.btn_Connect.hide() # self.ui.btn_Connect.clicked.connect(self.Connect) self.ui.btn_Game.clicked.connect(self.Game) self.ui.btn_Startstreaming.clicked.connect(self.SendStream) self.ui.btn_Recievefile.clicked.connect(self.RecieveFile) self.ui.btn_Sendfile.clicked.connect(self.Sendfile) # self.ui.btn_Startstreaming.clicked.connect(self.Startstreaming) self.x = 0 self.y = 0 ## self.ui.btn_Sendfile.clicked.connect(self.browse) def GoToStreamingWidget(self): self.ui.stackedWidget.setCurrentIndex(2) def EndGameConnection(self): self.mySocket.close() def ReturnBack(self): self.ui.stackedWidget.setCurrentIndex(0) def toggle(self, label): QApplication.processEvents() self.updateButtons(label) data = self.mySocket.recv(1024).decode() print('Received from server: ' + data) QApplication.processEvents() self.checkLabel(data) # def Statchat(self): # host = self.host # port = 8001 # mySocket = socket.socket() # mySocket.connect((host,port)) # message = "habiba: " + input(" -> ") # while message != 'q': # mySocket.send(message.encode()) # data = mySocket.recv(1024).decode() # print ('Received from server: ' + data) # message = "habiba: " + input(" -> ") # mySocket.close() # print("close connection of chat") def StartGameConnection(self): try: self.port = 7000 self.mySocket = socket.socket() self.mySocket.connect((self.host, self.port)) print("connection established") except: QMessageBox.question(self, 'ERROR', "Connection Failed", QMessageBox.Yes) def recieveStream(self): print('waiting for connection') HOST = '' PORT = 4000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Socket created') s.bind((HOST, PORT)) print('Socket bind complete') s.listen(10) print('Socket now listening') conn, addr = s.accept() data = b'' ### CHANGED payload_size = struct.calcsize("L") ### CHANGED while True: # Retrieve message size while len(data) < payload_size: data += conn.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("L", packed_msg_size)[0] ### CHANGED # Retrieve all data based on message size while len(data) < msg_size: data += conn.recv(4096) frame_data = data[:msg_size] data = data[msg_size:] # Extract frame frame = pickle.loads(frame_data) # Display cv2.imshow('frame', frame) cv2 if cv2.waitKey(1) & 0xFF == ord('q'): s.close() print('socket closed') break def SendStream(self): try: print("stream") cap = cv2.VideoCapture(0) clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect((self.host, 5000)) print("connected stream") while True: ret, frame = cap.read() # Serialize frame data = pickle.dumps(frame) # Send message length first message_size = struct.pack("L", len(data)) ### CHANGED # Then data clientsocket.sendall(message_size + data) print("socket camera closed") clientsocket.close() except: QMessageBox.question(self, 'ERROR', "Connection Failed", QMessageBox.Yes) def checkLabel(self, data): if data == "l1": self.updateButtons(self.ui.lbl_1) elif data == "l2": self.updateButtons(self.ui.lbl_2) elif data == "l3": self.updateButtons(self.ui.lbl_3) elif data == "l4": self.updateButtons(self.ui.lbl_4) elif data == "l5": self.updateButtons(self.ui.lbl_5) elif data == "l6": self.updateButtons(self.ui.lbl_6) elif data == "l7": self.updateButtons(self.ui.lbl_7) elif data == "l8": self.updateButtons(self.ui.lbl_8) elif data == "l9": self.updateButtons(self.ui.lbl_9) def updateButtons(self, label): label.setEnabled(False) label.setText(self.current) if (self.current == 'X'): self.current = 'O' else: self.current = 'X' self.numOfClicks = self.numOfClicks + 1 if (self.numOfClicks > 4): self.checkForWin() print(self.numOfClicks) def disableAllLabels(self): self.ui.lbl_1.setEnabled(False) self.ui.lbl_2.setEnabled(False) self.ui.lbl_3.setEnabled(False) self.ui.lbl_4.setEnabled(False) self.ui.lbl_5.setEnabled(False) self.ui.lbl_6.setEnabled(False) self.ui.lbl_7.setEnabled(False) self.ui.lbl_8.setEnabled(False) self.ui.lbl_9.setEnabled(False) def enableAllLabels(self): self.ui.lbl_1.setEnabled(True) self.ui.lbl_2.setEnabled(True) self.ui.lbl_3.setEnabled(True) self.ui.lbl_4.setEnabled(True) self.ui.lbl_5.setEnabled(True) self.ui.lbl_6.setEnabled(True) self.ui.lbl_7.setEnabled(True) self.ui.lbl_8.setEnabled(True) self.ui.lbl_9.setEnabled(True) def clearAllLabels(self): self.ui.lbl_1.clear() self.ui.lbl_2.clear() self.ui.lbl_3.clear() self.ui.lbl_4.clear() self.ui.lbl_5.clear() self.ui.lbl_6.clear() self.ui.lbl_7.clear() self.ui.lbl_8.clear() self.ui.lbl_9.clear() self.current = 'X' self.numOfClicks = 0 self.isWiner = 0 self.winer = '' def restartGame(self): self.disableAllLabels() buttonReply = QMessageBox.question(self, 'PyQt5 message', "Restart Game?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if buttonReply == QMessageBox.Yes: self.clearAllLabels() self.enableAllLabels() else: print('No clicked.') def checkForWin(self): if self.ui.lbl_1.text() == self.ui.lbl_2.text( ) and self.ui.lbl_3.text() == self.ui.lbl_2.text() != "": self.bgrb("one") elif self.ui.lbl_4.text() == self.ui.lbl_5.text( ) and self.ui.lbl_6.text() == self.ui.lbl_5.text() != "": self.bgrb("two") elif self.ui.lbl_7.text() == self.ui.lbl_8.text( ) and self.ui.lbl_9.text() == self.ui.lbl_8.text() != "": self.bgrb("three") elif self.ui.lbl_1.text() == self.ui.lbl_5.text( ) and self.ui.lbl_9.text() == self.ui.lbl_5.text() != "": self.bgrb("four") elif self.ui.lbl_3.text() == self.ui.lbl_5.text( ) and self.ui.lbl_7.text() == self.ui.lbl_5.text() != "": self.bgrb("five") elif self.ui.lbl_1.text() == self.ui.lbl_4.text( ) and self.ui.lbl_7.text() == self.ui.lbl_4.text() != "": self.bgrb("six") elif self.ui.lbl_2.text() == self.ui.lbl_5.text( ) and self.ui.lbl_8.text() == self.ui.lbl_5.text() != "": self.bgrb("seven") elif self.ui.lbl_3.text() == self.ui.lbl_6.text( ) and self.ui.lbl_9.text() == self.ui.lbl_6.text() != "": self.bgrb("eight") else: if (self.numOfClicks > 8): print('restart game') QMessageBox.question(self, 'Bummer!!', "Its a DRAW !!!!!", QMessageBox.Yes) self.restartGame() def bgrb(self, text): self.isWiner = 1 self.winer = self.current print("7sl restart bssbb or: " + text) QMessageBox.question(self, 'Winner', "Player" + self.winer + "Has Won", QMessageBox.Yes) self.restartGame() def showText1(self, event): QApplication.processEvents() self.ui.lbl_1.setText(self.current) message = "l1" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_1) def showText2(self, event): QApplication.processEvents() self.ui.lbl_2.setText(self.current) message = "l2" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_2) def showText3(self, event): QApplication.processEvents() self.ui.lbl_3.setText(self.current) message = "l3" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_3) def showText4(self, event): QApplication.processEvents() self.ui.lbl_4.setText(self.current) message = "l4" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_4) def showText5(self, event): QApplication.processEvents() self.ui.lbl_5.setText(self.current) message = "l5" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_5) def showText6(self, event): QApplication.processEvents() self.ui.lbl_6.setText(self.current) message = "l6" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_6) def showText7(self, event): QApplication.processEvents() self.ui.lbl_7.setText(self.current) message = "l7" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_7) def showText8(self, event): QApplication.processEvents() self.ui.lbl_8.setText(self.current) message = "l8" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_8) def showText9(self, event): QApplication.processEvents() self.ui.lbl_9.setText(self.current) message = "l9" self.mySocket.send(message.encode()) self.toggle(self.ui.lbl_9) def Connect(self): self.ui.stackedWidget.setCurrentIndex(3) # text1 , result = QInputDialog.getText (self, 'Info' ,"Enter IP" ) # if result== True: # self.ui.ln_IP.setText(str(text1)) # text2 , result = QInputDialog.getText (self, 'Info' ,"Enter port " ) # if result== True: # self.ui.ln_Port.setText(str(text2)) # # self.style() # #self.connection(str(text1),int(text2)) # self.ui.ln_name2.setText(str(self.ui.ln_name.text())) # self.ui=form2() # self.ui.setupUi(self) # app = QtWidgets.QApplication(sys.argv) # self.close() # application = p2() # application.show() # sys.exit(app.exec_()) def Game(self): self.ui.stackedWidget.setCurrentIndex(1) self.clearAllLabels() self.enableAllLabels() self.ui.ln_name2.setText(self.ui.ln_name.text()) def mousePressEvent(self, event): self.x = event.pos().x() self.y = event.pos().y() def RecieveFile(self): try: print("butoon recieved clicked") soc = socket.socket() soc.connect((self.host, 8080)) print("socketconnected") with soc, open("file", 'wb') as file: while True: recvfile = soc.recv(4096) print(recvfile) if not recvfile: break file.write(recvfile) print("File has been received.") soc.close() try: image = mpimg.imread("file") plt.imshow(image) plt.show() except: # # cap = cv2.VideoCapture(0) capture = cv2.VideoCapture('file') while (True): ret, frame = capture.read() cv2.imshow('video', frame) if cv2.waitKey(27) & 0xFF == ord('q'): break # When everything done, release the capture capture.release() cv2.destroyAllWindows() except: QMessageBox.question(self, 'ERROR', "Connection Failed", QMessageBox.Yes) # self.filename, _filter=QFileDialog.getOpenFileName(self,"open file"," ","Image File(*.png *.jpg *.jpeg *.bmp)") # if self.filename: # #imagePath = self.filename def Sendfile(self): try: self.filename, _filter = QFileDialog.getOpenFileName( self, "open file", " ", "Image File(*.*)") if self.filename: soc = socket.socket() soc.bind(('', 8080)) soc.listen(1) print('waiting for connection...') with soc: con, addr = soc.accept() print('server connected to', addr) with con: filename = self.filename print(filename) with open(filename, 'rb') as file: sendfile = file.read() con.sendall(sendfile) print('file sent') soc.close() except: QMessageBox.question(self, 'ERROR', "Connection Refused", QMessageBox.Yes) def connection(self, Ip, portnumber): cap = cv2.VideoCapture(0) clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect((Ip, portnumber)) while True: ret, frame = cap.read() # Serialize frame data = pickle.dumps(frame) # Send message length first message_size = struct.pack("L", len(data)) ### CHANGED # Then data clientsocket.sendall(message_size + data) QApplication.processEvents()
from PyQt5.QtWidgets import * from app import Ui_MainWindow if __name__ == "__main__": import sys app = QApplication(sys.argv) MainWindow = QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())