Widget and Textinput doesn't appear on Kivy Screen - widget

Everything seems to be perfect but on Kivy screen, nothing appears, just black screen! I've tried to rearrange the positions of imports and even installed the pygame but still the problem keeps persisting!
import kivy
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.app import App
class MyGrid(GridLayout):
def __init___(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text="Name: "))
self.name = TextInput(multiline=False)
self.add_widget(self.name)
self.add_widget(Label(text="Last Name: "))
self.lastname = TextInput(multiline=False)
self.add_widget(self.lastname)
self.add_widget(Label(text="Email: "))
self.email = TextInput(multiline=False)
self.add_widget(self.email)
class MyApp(App):
def build(self):
return MyGrid()
if __name__ == "__main__":
MyApp().run()

There is an extra underscore on line def __init___(self, **kwargs): after init word. Please remove that and then it should run ok.

Related

Same dash dashboard template with different dataset inside a flask app. How to do it?

I'm looking for the simplest way to generate the same dash dashboard X times with different dataset.
Each dashboard is a single page and the main app is a flask app.
The goal is to have a dashboard template running on different dash instance with different dataset.
I started with the following code, but I'm struggling when dash pages include callbacks i.e when html.Div([html.H1('Hi there, I am app1 for reports')]) turns into a bigger function with callback
import dash
import dash_html_components as html
from flask import Flask, render_template, redirect
from werkzeug.middleware.dispatcher import DispatcherMiddleware
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello from Flask!'
#app.route('/test2')
def t2():
return render_template('test2.html')
dash_app1 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard/' )
dash_app2 = dash.Dash(__name__, server = app, url_base_pathname='/reports/')
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for reports')])
dash_app2.layout = html.Div([html.H1('Hi there, I am app2 for reports')])
#app.route('/dashboard')
def render_dashboard():
return redirect('/dash1')
#app.route('/reports')
def render_reports():
return redirect('/dash2')
app = DispatcherMiddleware(app, {
'/dash1': dash_app1.server,
'/dash2': dash_app2.server
})
So my question is what is the best way/architecture to manage muti dash dashboards, based on the same template, running different data ?
In case it might help, I found a solution encapsulating the layout, callbacks and return function into a class.
flask_app.py
from flask import Flask, render_template, redirect
import dash
from apps.dashboard1 import Dashboard1
from apps.dashboard2 import Dashboard2
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello from Flask!'
#app.route('/test')
def test():
return render_template('test.html')
dash_app1 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard1/' )
dash_app1.config.suppress_callback_exceptions = True
dash_app1.layout = Dashboard1(dash_app1).layout
#app.route('/dashboard1')
def render_dashboard():
return redirect('/dash1')
dash_app2 = dash.Dash(__name__, server = app, url_base_pathname='/dashboard2/')
dash_app2.config.suppress_callback_exceptions = True
dash_app2.layout = Dashboard2(dash_app2).layout
#app.route('/dashboard2')
def render_dashboard2():
return redirect('/dash2')
if __name__ == '__main__':
app.run(debug=True)
apps/dashboard1.py
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
class Dashboard1:
def __init__(self, app_dependency):
self.app_dependency = app_dependency
html.P("Your code here"),
dcc.Dropdown(...),
...
dcc.Graph(id="pie-chart"),
])
#self.app_dependency.callback(
Output("pie-chart", "figure"),
Input('organisations', 'value'))
def update_output_div(selected_org):
your_update_function
return your_outputs

The PyQt5 Application Stop completely

I have a problem here with my Pyqt5 app when I try to add the user input to mysql database in the Add_car_info function. When I press the button to add the info the app stop working and gives me this error message. tested on windows.
here is the code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import loadUiType
from PyQt5 import QtWidgets, QtGui
import threading
import sys
import os
from os import path
import mysql.connector
import MySQLdb
#get the ui file
FORM_CLASS,_=loadUiType(path.join(path.dirname(__file__),"main.ui"))
class MainApp(QMainWindow, FORM_CLASS):
def __init__(self, parent=None):
super(MainApp,self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.Handel_Ui()
self.Handel_DB_Connect()
self.Handel_Buttons()
self.Handel_DB_Connect()
def Handel_Ui(self):
self.setWindowTitle('Car_System')
self.tabWidget.tabBar().setVisible(False)
def Handel_DB_Connect(self):
db = mysql.connector.connect(database='mydb',
host='localhost',
user='root',
port='3309',
password='toor')
self.cur = db.cursor()
QApplication.processEvents()
def Handel_Buttons(self):
self.pushButton.clicked.connect(self.Add_car_info)
self.pushButton_2.clicked.connect(self.Update_car_info)
self.pushButton_3.clicked.connect(self.Delete_car_info)
self.pushButton_4.clicked.connect(self.Add_fuel_info)
self.pushButton_9.clicked.connect(self.Update_fuel_info)
self.pushButton_5.clicked.connect(self.Add_maintenance_info)
self.pushButton_6.clicked.connect(self.Update_maintenance_info)
self.pushButton_7.clicked.connect(self.Add_Licence_info)
self.pushButton_8.clicked.connect(self.Update_Licence_info)
self.pushButton_17.clicked.connect(self.Add_Revenus_info)
self.pushButton_18.clicked.connect(self.Update_Revenus_info)
self.pushButton_19.clicked.connect(self.Add_Rents_info)
self.pushButton_20.clicked.connect(self.Update_Rents_info)
self.pushButton_34.clicked.connect(self.Add_elewater_info)
self.pushButton_33.clicked.connect(self.Update_elewater_info)
def Add_car_info(self):
car_number = self.lineEdit_12.text()
owner_company = self.lineEdit_10.text()
branch = self.lineEdit_8.text()
service_mode = self.comboBox.currentIndex()
shaceh_number = self.lineEdit_4.text()
motor_number = self.lineEdit_2.text()
fuel_type = self.comboBox_2.currentIndex()
car_type = self.lineEdit_11.text()
car_model = self.lineEdit_9.text()
car_load = self.lineEdit_7.text()
car_wight = self.lineEdit_5.text
car_shape = self.lineEdit_3.text()
car_color = self.lineEdit.text()
self.cur.execute('''INSERT INTO car_info(car_number, owner_company, branch, service_mode, shaceh_number, motor_number, fuel_type, car_type, car_model, car_load, car_weight, car_shape, car_color)'
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''' , (car_number,owner_company,branch,service_mode,shaceh_number,motor_number,fuel_type,car_type,car_model,car_load,car_wight,car_shape,car_color))
QApplication.processEvents()
print('Done')
def Update_car_info(self):
pass
def Delete_car_info(self):
pass
def Add_fuel_info(self):
pass
def Update_fuel_info(self):
pass
def Add_maintenance_info(self):
pass
def Update_maintenance_info(self):
pass
def Add_Licence_info(self):
pass
def Update_Licence_info(self):
pass
def Add_Revenus_info(self):
pass
def Update_Revenus_info(self):
pass
def Add_Rents_info(self):
pass
def Update_Rents_info(self):
pass
def Add_elewater_info(self):
pass
def Update_elewater_info(self):
pass
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == '__main__':
main()
thank you for your attantion and have a good day.

putting HTML output from SHAP into the Dash output layout callback

I am trying to make a dashboard where the output from shap forceplot is illustrated. Shap.forceplot is HTML decorated with json. The example is here
I made a very simple dashboard using the tutorial which should plot the desirable figure after clicking the submit
here is the code
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
from sqlalchemy import create_engine
import shap
from sources import *
import xgboost
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Input(id='input-cvr-state', type='text', value='12'),
html.Button(id='submit-button', n_clicks=0, children='Submit'),
html.Div(id='output-state'),
html.Div(id='output-shap')
])
#app.callback(Output('output-shap', 'children'),
[Input('submit-button', 'n_clicks')],
[State('input-cvr-state', 'value')])
def update_shap_figure(n_clicks, input_cvr):
shap.initjs()
# train XGBoost model
X,y = shap.datasets.boston()
model = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100)
# explain the model's predictions using SHAP values(same syntax works for LightGBM, CatBoost, and scikit-learn models)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
# visualize the first prediction's explanation
return(shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])) # matplotlib=True
if __name__ == '__main__':
app.run_server(debug=True)
I managed it by following steps:
import shap
from shap.plots._force_matplotlib import draw_additive_plot
# ... class dashApp
# ... callback as method
# matplotlib=False => retrun addaptativevisualizer,
# if set to True the visualizer will render the result is the stdout directly
# x is index of wanted input
# class_1 is ma class to draw
force_plot = shap.force_plot(
self.explainer.expected_value[class_1],
self.shap_values[class_1][x[0], :],
self.data.iloc[x, :].drop(columns=["TARGET"], errors="ignore"),
matplotlib=False
)
# set show=False to force the figure to be returned
force_plot_mpl = draw_additive_plot(force_plot.data, (30, 7), show=False)
return figure_to_html_img(force_plot_mpl)
def figure_to_html_img(figure):
""" figure to html base64 png image """
try:
tmpfile = io.BytesIO()
figure.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')
shap_html = html.Img(src=f"data:image/png;base64, {encoded}")
return shap_html
except AttributeError:
return ""
The result will be like it
An alternative is to use html.IFrame which will produce a better looking and fully interactive plot.
Here's an example that can be used directly as an Output
def _force_plot_html(*args):
force_plot = shap.force_plot(*args, matplotlib=False)
shap_html = f"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>"
return html.Iframe(srcDoc=shap_html,
style={"width": "100%", "height": "200px", "border": 0})

connect to MySQL data base with QSqlDatabase pyqt4

im new to python code, QT and MySQL, i wanna show a data base in a QtableView but i cant it.
i dont know whats happend, the error is ('QSqlDatabase' object has no attribute 'setHotsName')
the code is:
# -*- coding: utf-8 -*-
import sys
import mysql.connector
from PyQt4 import QtSql, QtCore, QtGui, uic
form_class = uic.loadUiType("dialog.ui")[0]
def crearConexion():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHotsName('localhots')
db.setDatabaseName('Registro')
db.setUserName('root')
db.setPassword('xxxx')
db.open()
print(db.lastError().text())
return True
class MiClase(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.model=QtSql.QSqlTableModel(self)
self.model.setTable("RegistroIN")
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.select()
self.tableView.setModel(self.model)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
if not crearConexion():
sys.exit(1)
MiApp = MiClase()
MiApp.show()
sys.exit(app.exec_())
somebody that help me? thank you.

deleting a parent widget through a child QPushButton pyqt

It's been a while I'm searching all over the internet for that, but still couldn't get the answer... basically I have a QVBoxLayout which contains several frames - and each frame contains a button which function is to delete its parent frame. The main code was created using QT Designer and pyuic4. I wrote the two additional functions, one works perfectly ("createFrame") but I'm struggling with the "deleteFrame" one. the label inside the frame shows the index of that frame in the vert_layout "array". the problem I noted on my code is that, using it that way, I can only delete the last frame added. So, can someone help me with this issue?
please see my code below:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
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)
#Custom button that sends out its own instance as the signal
class MyPushButton(QtGui.QPushButton):
mySignal = QtCore.pyqtSignal(QtGui.QWidget)
def mousePressEvent(self, *args, **kwargs):
self.mySignal.emit(self)
class Functions:
def createFrame(self,mainWindow):
#just local frame no need to store it in the class
frame = QtGui.QFrame()
frame.setGeometry(QtCore.QRect(10, 10, 241, 61))
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
frame.setObjectName(_fromUtf8("frame"))
pushButton_2 = MyPushButton(frame)
pushButton_2.setGeometry(QtCore.QRect(94, 10, 141, 41))
pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
label = QtGui.QLabel(frame)
label.setGeometry(QtCore.QRect(20, 10, 71, 41))
label.setFrameShape(QtGui.QFrame.NoFrame)
label.setAlignment(QtCore.Qt.AlignCenter)
#the vert_layout belongs to class Ui_MainWindow
mainWindow.vert_layout.addWidget(frame)
label.setObjectName(_fromUtf8("label"))
label.setText(str(mainWindow.vert_layout.indexOf(frame)))
pushButton_2.setText(_translate("MainWindow", "delete this frame and all\n its childs", None))
pushButton_2.mySignal.connect(self.deleteFrame)
#my initial idea was to include the mainWindow (instance of
#Ui_MainWindow class in order to use vert_layout - but apparently
#I need to modify the signal as well, right?
def deleteFrame(self,ref,mainWindow):
#finding the index of the FRAME (mybutton's parent)
#that is to be deleted
frame = mainWindow.vert_layout.itemAt(self.vert_layout.indexOf(ref.parent()))
widget = frame.widget()
if widget is not None:
widget.deleteLater()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 284)
self.vert_layout = QtGui.QVBoxLayout()
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(10, 10, 281, 261))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 277, 257))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setLayout(self.vert_layout)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 20, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
f = Functions()
self.pushButton.clicked.connect(lambda: f.createFrame())
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "create", None))
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
All you are currently doing is deleting the self.frame widget each time.
So only the last created one gets deleted. And not the one you actually click on.
Modified your code for what you need. Hope it helps you understand.
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
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)
#Custom button that sends out its own instance as the signal
class MyPushButton(QtGui.QPushButton):
mySignal = QtCore.pyqtSignal(QtGui.QWidget)
def mousePressEvent(self, *args, **kwargs):
self.mySignal.emit(self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 284)
self.vert_layout = QtGui.QVBoxLayout()
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(10, 10, 281, 261))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 277, 257))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setLayout(self.vert_layout)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 20, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.clicked.connect(lambda: self.createFrame())
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "create", None))
def createFrame(self):
#just local frame no need to store it in the class
frame = QtGui.QFrame()
frame.setGeometry(QtCore.QRect(10, 10, 241, 61))
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
frame.setObjectName(_fromUtf8("frame"))
pushButton_2 = MyPushButton(frame)
pushButton_2.setGeometry(QtCore.QRect(94, 10, 141, 41))
pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
label = QtGui.QLabel(frame)
label.setGeometry(QtCore.QRect(20, 10, 71, 41))
label.setFrameShape(QtGui.QFrame.NoFrame)
label.setAlignment(QtCore.Qt.AlignCenter)
self.vert_layout.addWidget(frame)
label.setObjectName(_fromUtf8("label"))
label.setText(str(self.vert_layout.indexOf(frame)))
pushButton_2.setText(_translate("MainWindow", "delete this frame and all\n its childs", None))
pushButton_2.mySignal.connect(self.deleteFrame)
def deleteFrame(self,ref):
#finding the index of the FRAME (mybutton's parent)
#that is to be deleted
frame = self.vert_layout.itemAt(self.vert_layout.indexOf(ref.parent()))
widget = frame.widget()
if widget is not None:
widget.deleteLater()
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())