def showImage(self, text):
try:
if text == 'Show Red':
RPiCamera.showImage(self.rgb_array, 'r')
elif text == 'Show Green':
RPiCamera.showImage(self.rgb_array, 'g')
elif text == 'Show Blue':
RPiCamera.showImage(self.rgb_array, 'b')
else:
RPiCamera.showImage(self.rgb_array)
except ValueError:
mb = QMessageBox()
mb.setIcon(QMessageBox.Information)
mb.setWindowTitle('Error')
mb.setText('Array not loaded, make sure you take picture or import an image first.')
mb.setStandardButtons(QMessageBox.Ok)
mb.show()
python类Ok()的实例源码
def add_preset(self):
name = self.nameLineEdit.text()
ip = self.ipLineEdit.text()
port = self.portSpinBox.value()
password = self.passwordLineEdit.text()
# Make sure password is non if empty
if not password:
password = None
if not name:
QMessageBox().warning(self, "Missing name", "Fill the name of preset", QMessageBox.Ok)
return
if not IpHelper.is_valid_ipv4(ip):
QMessageBox().warning(self, "Invalid IP", "The IP address has invalid format", QMessageBox.Ok)
return
Settings().wifi_presets.append((name, ip, port, password))
self.update_preset_list()
def connect(self, endpoint: str, payload: object=None) -> object:
try:
headers = {
'Authorization': 'Bearer %s' % self.api_token,
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
}
res = requests.post('%s%s' % (self.api_url, endpoint), headers=headers, data=payload,
proxies=self.proxy, verify=False)
return res.json()
except HTTPError:
print(sys.exc_info())
QMessageBox.critical(self, 'ERROR NOTIFICATION',
'<h3>Real-Debrid API Error</h3>' +
'A problem occurred whilst communicating with Real-Debrid. Please check your '
'Internet connection.<br/><br/>' +
'<b>ERROR LOG:</b><br/>(Error Code %s) %s<br/>%s'
% (qApp.applicationName(), HTTPError.code, HTTPError.reason), QMessageBox.Ok)
# self.exit()
def add_uri(self) -> None:
user, passwd = '', ''
if len(self.rpc_username) > 0 and len(self.rpc_password) > 0:
user = self.rpc_username
passwd = self.rpc_password
elif len(self.rpc_secret) > 0:
user = 'token'
passwd = self.rpc_secret
aria2_endpoint = '%s:%s/jsonrpc' % (self.rpc_host, self.rpc_port)
headers = {'Content-Type': 'application/json'}
payload = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'aria2.addUri',
'params': ['%s:%s' % (user, passwd), [self.link_url]]},
sort_keys=False).encode('utf-8')
try:
req = Request(aria2_endpoint, headers=headers, data=payload)
res = urlopen(req).read().decode('utf-8')
jsonres = json.loads(res)
# res = requests.post(aria2_endpoint, headers=headers, data=payload)
# jsonres = res.json()
self.aria2Confirmation.emit('result' in jsonres.keys())
except HTTPError:
print(sys.exc_info())
QMessageBox.critical(self, 'ERROR NOTIFICATION', sys.exc_info(), QMessageBox.Ok)
self.aria2Confirmation.emit(False)
# self.exit()
def __init__(self, parent=None):
super(VideoService, self).__init__(parent)
self.parent = parent
self.logger = logging.getLogger(__name__)
try:
self.backends = VideoService.findBackends()
self.proc = VideoService.initProc()
if hasattr(self.proc, 'errorOccurred'):
self.proc.errorOccurred.connect(self.cmdError)
self.lastError = ''
self.media, self.source = None, None
self.keyframes = []
self.streams = Munch()
except FFmpegNotFoundException as e:
self.logger.exception(e.msg, exc_info=True)
QMessageBox.critical(getattr(self, 'parent', None), 'Missing libraries', e.msg, QMessageBox.Ok)
def install(self):
infoBox = QMessageBox()
infoBox.setIcon(QMessageBox.Information)
infoBox.setText("Your programs are being installed.Please wait")
infoBox.setWindowTitle("Information")
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.exec_()
#BashCommands.StartRun()
self.getItems()
infoBox = QMessageBox()
infoBox.setIcon(QMessageBox.Information)
infoBox.setText("Your programs installed ")
infoBox.setWindowTitle("Information")
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.exec_()
# When clicked update button
def check_null(self):
"""
check the required options
:return:
"""
is_none = False
type_info = ''
case_name = self.case_name_line_edit.text().strip()
content = self.editor_text_edit.toPlainText().strip()
if not case_name:
is_none = True
type_info += "Case Name"
if not content:
is_none = True
if not type_info:
type_info += "Content"
else:
type_info += ", Content"
if is_none:
self.message_box.warning(self, "Message", type_info + " is required.", QMessageBox.Ok)
return is_none
def connectToDatabase(db, user, psswrd, host):
try:
global conn
conn = pymysql.connect(
db=db,
user=user,
passwd=psswrd,
host=host
)
global data
data = getAndSetData(conn)
return conn, data
except pymysql.err.OperationalError:
Q = QMessageBox()
Q = QMessageBox.information(Q, 'Error', 'Your username and/or password was incorrect. Please try again.', QMessageBox.Ok)
return None, None
def logout_warn(self):
"""
Description: Called if the warn_autologout setting has been set in the config. It
will warn user to reset their idle, otherwise an enforced logout will
be performed by calling the logout() method.
Arguments: None
Returns: Nothing
"""
self.autologoutwarnwin = QMessageBox(None)
self.autologoutwarnwin.setIcon(QMessageBox.Warning)
self.autologoutwarnwin.setText(_('auto_logout_warn'))
self.autologoutwarnwin.setWindowTitle(_('auto_logout_warn_title'))
self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
self.autologoutwarnwin.exec_()
def process_start(self, row, process, warn=True):
"""
Handle the startup of a B3 process.
:param row: the number of the row displaying the process state
:param process: the QProcess instance to start
:param warn: whether to warn the user of a startup failure or not
"""
if process.state() != QProcess.Running:
# refresh the config before running
process.config = process.config_path
self.paint_row(row)
if process.isFlag(CONFIG_READY):
process.stateChanged.connect(partial(self.paint_row, row=row))
process.start()
else:
if warn:
suffix = 'not found' if process.isFlag(CONFIG_FOUND) else 'not valid'
reason = 'configuration file %s: %s' % (suffix, process.config_path)
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('%s startup failure: %s' % (process.name, reason))
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
def update_database(self):
"""
Display the 'database update' dialog.
"""
self.show()
is_something_running = False
for x in B3App.Instance().processes:
if x.state() == QProcess.Running:
is_something_running = True
break
if is_something_running:
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Information)
msgbox.setWindowTitle('NOTICE')
msgbox.setText('Some B3 processes are still running: you need to terminate them to update B3 database.')
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
else:
update = UpdateDatabaseDialog(self.centralWidget())
update.show()
def with_btn_click(self):
if self.input_PW.text() == '':
QMessageBox.warning(self, '?? ??', '????? ??? ???')
return
answer = QMessageBox.warning(self, '?? ??', '??? ?? ???????\n??? ??? ??? ??????.', QMessageBox.Ok|QMessageBox.No)
if (answer == QMessageBox.No):
return
else:
mysocket.sendMsg(s, '2', key)
mysocket.sendMsg(s, self.input_PW.text(), key)
result = mysocket.getMsg(s, key)
if result == 'PW different' or result == 'PW different ':
print(result)
QMessageBox.warning(self, '?? ??', '?? ?? ??')
return
else:
QMessageBox.information(self, '?? ??', '???? ??????. ??~')
self.hide()
tmp = MainWidget()
tmp.hide()
tmp = Login()
tmp.run()
def with_btn_click(self):
if self.input_PW.text() == '':
QMessageBox.warning(self, '?? ??', '????? ??? ???')
return
answer = QMessageBox.warning(self, '?? ??', '??? ?? ???????\n??? ??? ??? ??????.', QMessageBox.Ok|QMessageBox.No)
if (answer == QMessageBox.No):
return
else:
QMessageBox.information(self, '??? ??', '?? ????')
"""
mysocket.sendMsg(s, '2', key)
mysocket.sendMsg(s, self.input_PW.text(), key)
result = mysocket.getMsg(s, key)
if result == 'PW different' or result == 'PW different ':
QMessageBox.warning(self, '?? ??', '?? ?? ??')
return
else:
QMessageBox.information(self, '?? ??', '???? ??????. ??~')
??? ???.
"""
def tempPlot(self):
try:
self.y_title_axis = ['Temperature Plot', 'Temperature vs Time', 't(s)', 'T(C)', 'Sensor']
MultiPlot.Plot(self.tf, len(self.ids), self.y_title_axis)
except KeyError:
mb = QMessageBox()
mb.setIcon(QMessageBox.Information)
mb.setWindowTitle('Error')
mb.setText('No temperature sensor connected.')
mb.setStandardButtons(QMessageBox.Ok)
mb.show()
def pumppowerchange(self):
try:
if self.pumppwmvalue > 100:
raise ValueError
else:
self.PUMPPWM.setIntensity(self.pumppwmvalue)
except ValueError:
mb = QMessageBox()
mb.setIcon(QMessageBox.Information)
mb.setWindowTitle('Error')
mb.setText('Please type in a value between 0-100.')
mb.setStandardButtons(QMessageBox.Ok)
mb.show()
def showPlots(self):
try:
RPiCamera.showPlot(self.rgb_array)
self.statusbar = 'Ready'
except ValueError:
mb = QMessageBox()
mb.setIcon(QMessageBox.Information)
mb.setWindowTitle('Error')
mb.setText('Array not loaded, make sure you take picture or import an image first.')
mb.setStandardButtons(QMessageBox.Ok)
mb.show()
def spawn_window(parent, node, iface_name):
driver = node.can_driver
if not slcan_cli.CLIInterface.is_backend_supported(driver):
mbox = QMessageBox(parent)
mbox.setWindowTitle('Unsupported CAN Backend')
mbox.setText('CAN Adapter Control Panel cannot be used with the current CAN backend.')
mbox.setInformativeText('The current backend is %r.' % type(driver).__name__)
mbox.setIcon(QMessageBox.Information)
mbox.setStandardButtons(QMessageBox.Ok)
mbox.show() # Not exec() because we don't want it to block!
return
progress_dialog = QProgressDialog(parent)
progress_dialog.setWindowTitle('CAN Adapter Control Panel Initialization')
progress_dialog.setLabelText('Detecting CAN adapter capabilities...')
progress_dialog.setMinimumDuration(800)
progress_dialog.setCancelButton(None)
progress_dialog.setRange(0, 0)
progress_dialog.show()
def supported_callback(supported):
progress_dialog.close()
if not supported:
mbox = QMessageBox(parent)
mbox.setWindowTitle('Incompatible CAN Adapter')
mbox.setText('CAN Adapter Control Panel cannot be used with the connected adapter.')
mbox.setInformativeText('Connected SLCAN adapter does not support CLI extensions.')
mbox.setIcon(QMessageBox.Information)
mbox.setStandardButtons(QMessageBox.Ok)
mbox.show() # Not exec() because we don't want it to block!
return
slcp = slcan_cli.ControlPanelWindow(parent, slcan_iface, iface_name)
slcp.show()
slcan_iface = slcan_cli.CLIInterface(driver)
slcan_iface.check_is_interface_supported(supported_callback)
def _update_progress(self):
if self._transfer.error:
QMessageBox().critical(self, "Error", "File transfer failed.", QMessageBox.Ok)
self.reject()
elif self._transfer.cancelled:
self.reject()
elif self._transfer.finished:
sleep(0.5)
self.accept()
else:
self.progressBar.setValue(self._transfer.progress * 100)
def error(self, message):
msg = QMessageBox()
msg.setText(message)
msg.setStandardButtons(QMessageBox.Ok)
out = msg.exec_()
def on_click(self):
textboxValue = self.textbox.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)
self.textbox.setText("")
def errorHandler(self, msg: str, title: str=None) -> None:
qApp.restoreOverrideCursor()
QMessageBox.critical(self, 'An error occurred' if title is None else title, msg, QMessageBox.Ok)
logging.error(msg)
def update(self):
Update.Update()
infoBox = QMessageBox()
infoBox.setIcon(QMessageBox.Information)
infoBox.setText("Updated")
infoBox.setWindowTitle("Information")
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.exec_()
# When clicked about button
def error_dlg(parent,text):
msgBox = QMessageBox(parent)
msgBox.setIcon(QMessageBox.Critical)
msgBox.setText("gpvdm error:")
msgBox.setInformativeText(text)
msgBox.setStandardButtons(QMessageBox.Ok )
msgBox.setDefaultButton(QMessageBox.Ok)
reply = msgBox.exec_()
def delrow(self):
if self.ui.tableWidget.currentIndex().row() > -1:
self.model.removeRow(self.ui.tableWidget.currentIndex().row())
self.i -= 1
self.model.select()
self.ui.lcdNumber.display(self.i)
else:
QMessageBox.question(self,'Message', "Please select a row would you like to delete", QMessageBox.Ok)
self.show()
def updaterow(self):
if self.ui.tableWidget.currentIndex().row() > -1:
record = self.model.record(self.ui.tableWidget.currentIndex().row())
record.setValue("Name",self.ui.lineEdit.text())
record.setValue("Surname",self.ui.lineEdit_2.text())
record.setValue("DOB", self.ui.dateEdit.text())
record.setValue("Phone", self.ui.lineEdit_3.text())
self.model.setRecord(self.ui.tableWidget.currentIndex().row(), record)
else:
QMessageBox.question(self,'Message', "Please select a row would you like to update", QMessageBox.Ok)
self.show()
def show_dialog(self, grade, error):
grade_table = {'Information': 1, 'Warning': 2, 'Critical': 3, 'Question': 4}
dialog = QMessageBox()
dialog.setIcon(grade_table[grade])
dialog.setText(error.msg)
dialog.setWindowTitle(grade)
dialog.setStandardButtons(QMessageBox.Ok)
dialog.exec_()
def select_event(self):
"""
handle the select event
:return:
"""
self.result_widget.get_checked_data()
if not self.result_widget.checked_cases_message:
self.message_box.warning(self, "Message", "Please choose cases first.", QMessageBox.Ok)
return
id_list = []
for item in self.result_widget.checked_cases_message:
id_list.append(int(item["case_id"]))
self.select_case_signal.emit(id_list)
self.close() # close AddCase
def click_run_stop_btn(self):
"""
start or stop to run case
:return:
"""
devices = []
if self.running:
self.stop_case()
return
if not self.cases: # cases is null
self.message_box.warning(self, "Message", "Please add cases first.", QMessageBox.Ok)
return
try:
devices = self.tester.devices()
except Exception as e:
self.add_log("<font color='red'>" + str(e) + "</font>")
if not devices: # There is no device connected
self.message_box.warning(self, "Message", "Please connect the device to your computer.", QMessageBox.Ok)
return
self.add_device_widget = AddDeviceWidget()
self.add_device_widget.setWindowModality(Qt.ApplicationModal)
self.add_device_widget.add_log_signal.connect(self.add_log, Qt.QueuedConnection)
self.add_device_widget.run_case_signal.connect(self.run_case, Qt.QueuedConnection)
self.device_list_signal.connect(self.add_device_widget.add_radio_to_widget, Qt.QueuedConnection)
self.add_device_widget.show()
try:
self.device_list_signal.emit(devices)
except Exception as e:
self.add_log("<font color='red'><pre>" + str(e) + "</pre></font>")
def select_event(self):
"""
handle the select event
:return:
"""
self.handle_selected_device()
if not self.selected_device_list: # no device is selected
self.message_box.warning(self, "Message", "Please choose a device.", QMessageBox.Ok)
return
# case data handle
if not self.all_data_selected:
input_number = self.line_number_line_edit.text().strip()
if not input_number or (not input_number.isdigit()):
self.message_box.warning(self, "Message", "Please input the right line number.", QMessageBox.Ok)
return
if not (0 < int(input_number) <= self.data_count):
self.message_box.warning(self, "Message", "Please input the right line number.", QMessageBox.Ok)
return
self.selected_data_number = int(input_number)
if self.data_count is None:
# case run
self.run_case_signal.emit(self.selected_device_list)
self.close()
return
# editor run
self.run_editor_signal.emit(self.selected_device_list, self.selected_data_number)
self.close()
def start_rpc_server(self):
"""
start rpc server
:return:
"""
try:
self.tester.start_server()
except Exception as e:
logger.exception(str(e))
self.message_box.warning(self, "Message", "Fail to start RPC-Server, Please restart it in settings.",
QMessageBox.Ok)