How to display SQL data into GUI list widget? - python

I was wondering how to display information from an database table onto a listwidget or something similar. This is for a flashcard app, and the one questions is supposed to show at a time. Then when the click to reveal button is clicked the corresponding answer is supposed to show, but at the moment nothing is shown in the list widgets.
I don't understand why nothing is being shown in the GUI.
Here is my Code -
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
import flashcard
import os
import sqlite3
class FlashCardApp(QtGui.QMainWindow, flashcard.Ui_MainWindow):
def __init__(self):
super(self.__class__,self).__init__()
self.setupUi(self)
self.questions = []
self.answers = []
self.currentQ = 0
self.RevealAnswerBtn.clicked.connect(self.disA)
def dispQ(self):
print("display question {}".format(self.currentQ+1))
self.listQuestionWidget.clear()
if self.questions:
self.listQuestionWidget.addItem(self.questions[self.currentQ])
def disA(self):
self.listAnswerWidget.clear()
if self.answers:
self.listAnswerWidget.addItem(self.answers[self.currentQ])
def setData (self, questions, answers):
self.questions = questions
self.answers = answers
def run(self):
print ("start")
self.currentQ = 0
self.dispQ()
def main():
questions = []
answers = []
connection = sqlite3.connect("login.db")
c = connection.cursor()
c.execute ("SELECT Question FROM Flashcards")
resultq = c.fetchall()
questions.append(resultq)
c.execute ("SELECT Answer FROM Flashcards")
resulta = c.fetchall()
answers.append(resulta)
connection.close()
app = QtGui.QApplication(sys.argv)
form = FlashCardApp()
form.setData(questions,answers)
form.run()
form.show()
app.exec_()
if __name__ == '__main__':
main()
but then i get this error -
Traceback (most recent call last):
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 68, in <module>
main()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 63, in main
form.run()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 41, in run
self.dispQ()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 25, in dispQ
self.listQuestionWidget.addItem(self.questions[self.currentQ])
TypeError: arguments did not match any overloaded call:
QListWidget.addItem(QListWidgetItem): argument 1 has unexpected type 'list'
QListWidget.addItem(str): argument 1 has unexpected type 'list'

Related

sqlite3.OperationalError: no such table: departments

this error comes suddenly , i am sure the tables exists in database cause it was works nicely after that i dont know wht happnd the window couldn't shown up to me :
Traceback (most recent call last):
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 71, in <module>
window=MainWindow()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 12, in __init__
self.depts=Departments.get_all_depts()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\departments.py", line 18, in get_all_depts
result= cur.execute(sql).fetchall()
sqlite3.OperationalError: no such table: departments
this is departments.py :
from sqlite3 import connect
class Departments:
def __init__(self,dept_id,dept_name,location_id):
self.dept_id=dept_id
self.dept_name=dept_name
self.location_id=location_id
def __repr__(self):
return self.dept_name
#staticmethod
def get_all_depts():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT * FROM departments'
result= cur.execute(sql).fetchall()
result=[Departments(*row)for row in result]
return result
def saveToDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='INSERT INTO departments VALUES (:dept_id , :dept_name , :location_id)'
cur.execute(sql,self.__dict__)
conn.commit()
def deleteFromDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='DELETE FROM departments WHERE department_id = :dept_id'
cur.execute(sql,self.__dict__)
conn.commit()
and here app.py when i run it the error above shown up:
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *
from main_window import Ui_Form
from departments import Departments
from locats import locates
from emloyee import Employee
class MainWindow(QWidget,Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.depts=Departments.get_all_depts()
self.load_depts()
self.emps= Employee.get_all_emps()
self.load_emps()
self.cb_depts.currentIndexChanged.connect(self.select_depts)
self.le_search.textChanged.connect(self.search)
self.bt_add_dept.clicked.connect(self.show_add_depts_dialog)
self.bt_del_dept.clicked.connect(self.delet_dept)
def load_depts(self):
dept_names= [d.dept_name for d in self.depts]
self.cb_depts.addItems(dept_names)
def load_emps(self):
self.tb_emps.setRowCount(0)
for i,e in enumerate(self.emps):
self.tb_emps.insertRow(i)
for n,v in enumerate(e.__dict__.values()):
self.tb_emps.setItem(i,n,QTableWidgetItem(str(v)))
def select_depts(self,idx):
self.load_emps()
if idx !=0:
dept_i=self.depts[idx-1]
for i,e in enumerate(self.emps):
if e.dept_id != dept_i.dept_id:
self.tb_emps.hideRow(i)
def search(self):
self.load_emps()
text=self.le_search.text()
if text != "":
for i,e in enumerate (self.emps):
if not e.emp_name.startswith(text):
self.tb_emps.hideRow(i)
def show_add_depts_dialog(self):
dialog = loadUi("C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\add_depts.ui")
locs={str(l.location_id) for l in self.depts}
dialog.cb_locats.addItems(locs)
choice =dialog.exec()
if choice ==1:
dept = Departments(dialog.le_deps_id.text(),
dialog.le_deps_name.text(),
dialog.cb_locats.currentText())
self.depts.append(dept)
self.cb_depts.addItem(dept.dept_name)
dept.saveToDb()
def delet_dept(self):
idx=self.cb_depts.currentIndex()
if idx != 0:
self.cb_depts.removeItem(idx)
dept = self.depts.pop(idx-1)
dept.deleteFromDb()
app = QApplication([])
window=MainWindow()
window.show()
app.exec()
employee.py:
from sqlite3 import connect
class Employee:
def __init__(self,emp_id,emp_name,email,hire_date,job_id,salary,dept_id):
self.emp_id=emp_id
self.emp_name=emp_name
self.email=email
self.hire_date=hire_date
self.job_id=job_id
self.salary=salary
self.dept_id=dept_id
def __repr__(self):
return self.emp_name
#staticmethod
def get_all_emps():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT employee_id,last_name,email,hire_date,job_id,salary,department_id FROM employees'
result= cur.execute(sql).fetchall()
result=[Employee(*row)for row in result]
return result
tables are already existed i take screen shoot:
enter image description here
any help pls????????????????????????????????????????????????????

How do i set text input as int in kivy

i am trying to set the kivy textinput as an int to use it as a variable, which will be used to send a certain amount of messages.
This is my code:
import pyautogui
import time
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class layy(App):
def build(self):
b = Button(text='Start Spam')
b.bind(on_press=self.bott())
layout = BoxLayout(orientation='vertical')
sublay1 = BoxLayout(orientation='horizontal')
sublay2 = BoxLayout(orientation='horizontal')
sublay3 = BoxLayout(orientation='horizontal')
layout.add_widget(sublay1)
sublay1.add_widget(a)
layout.add_widget(sublay2)
sublay2.add_widget(c)
sublay2.add_widget(d)
layout.add_widget(sublay3)
sublay3.add_widget(b)
return layout
def bott(self):
global a
a = TextInput(hint_text='insert text to spam')
global c
c = TextInput(hint_text=' insert time till beginning',
input_filter='int')
global d
d = TextInput(hint_text='insert amount', input_filter='int')
value3 = a
global ti
ti = value3.text
ii = int(c)
tt = int(d)
base = 0
time.sleep(tt)
while base < ii:
pyautogui.typewrite(ti)
pyautogui.press('enter')
base = base + 1
if __name__ == '__main__':
layy().run()
This is the error:
Traceback (most recent call last):
File "/home/fares/PycharmProjects/droidspm/main.py", line 67, in <module>
layy().run()
File "/home/fares/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/kivy/app.py", line 949, in run
self._run_prepare()
File "/home/fares/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/kivy/app.py", line 919, in _run_prepare
root = self.build()
File "/home/fares/PycharmProjects/droidspm/main.py", line 14, in build
b.bind(on_press = self.bott())
File "/home/fares/PycharmProjects/droidspm/main.py", line 52, in bott
ii= int(c)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
Are there any tips? I tried converting c and d to strings first but i got this error instead:
ValueError: invalid literal for int() with base 10: '<kivy.uix.textinput.TextInput object at 0x7f16597e7900>'
I cant seem to resolve the error, and i cant find anything online on how to. sorry if this is simple, i'm new to python.
On these specific lines:
ii = int(c)
tt = int(d)
You already got text using text property here, but why not for above?
ti = value3.text
value3(= a), b and c is all TextInput instances, it's just like you've been expecting to get integer by doing int(dict).
Plus, UI programing is usually made up with callbacks, writing sequential code with widgets just don't makes any sense. I'm not sure if your code worked as you've intended or not, but function bott won't wait until you actually type in something and keep on.
Here's simple demonstration of how kivy program would look like instead.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class InputField(TextInput):
def __init__(self, **kwargs):
super().__init__(multiline=False, input_filter = "int", **kwargs)
self.bind(on_text_validate=self.on_enter)
def on_enter(self, value):
output = int(value.text)
print(f"{output} - type: {type(output)}")
class MainApp(App):
def build(self):
layout_main = BoxLayout()
layout_main.add_widget(InputField())
return layout_main
if __name__ == '__main__':
MainApp().run()
for respective input of (123, 1230908):
123 - type: <class 'int'>
1230938 - type: <class 'int'>
Just using class InputField where you used TextInput would be enough - though use of global is hardly recommended, it will work.

Type Error: argument 1 has unexpected type 'QPushButton'

I wrote this codes:
import sys
import os
from PyQt5 import QtWidgets
class Notepad(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.yazi_alani = QtWidgets.QTextEdit()
self.temizle = QtWidgets.QPushButton("Temizle")
self.kaydet = QtWidgets.QPushButton("Kaydet")
self.dosya_ac = QtWidgets.QPushButton("Dosya Aç")
v_box = QtWidgets.QVBoxLayout()
v_box.addWidget(self.yazi_alani)
v_box.addWidget(self.temizle)
v_box.addWidget(self.kaydet)
v_box.addWidget(self.dosya_ac)
self.setLayout(v_box)
self.setWindowTitle("Barış'ın Notepad Programı")
self.setGeometry(200,200,800,600)
self.temizle.clicked.connect(self.temizle)
self.kaydet.clicked.connect(self.kaydet)
self.dosya_ac.clicked.connect(self.dosya_ac)
self.show()
def temizle(self):
self.yazi_alani.clear()
def kaydet(self):
dosya_ismi = QtWidgets.QFileDialog.getSaveFileName(self,"Dosya Kaydet",os.getenv("HOME"))
with open (dosya_ismi[0],"w",encoding="utf-8") as file:
file.write(self.yazi_alani.toPlainText())
def dosya_ac(self):
dosya_ismi = QtWidgets.QFileDialog(self, "Dosya Aç", os.getenv("HOME"))
with open(dosya_ismi[0],"r",encoding="utf-8") as file:
self.yazi_alani.setText(file.read())
app = QtWidgets.QApplication(sys.argv)
pencere = Notepad()
sys.exit(app.exec())
I got this error:
Traceback (most recent call last):
File "C:/Users/noikp/Desktop/PyQt5 projem.py", line 41, in <module>
pencere = Pencere()
File "C:/Users/noikp/Desktop/PyQt5 projem.py", line 8, in __init__
self.init_ui()
File "C:/Users/noikp/Desktop/PyQt5 projem.py", line 28, in init_ui
self.temizle.clicked.connect(self.temizle)
TypeError: argument 1 has unexpected type 'QPushButton'
How can I solve this error?
It may be good if you answer fast...
pythonerrors
python
error
errors
errorrr
python3-x
You should rename your buttons or funcions.
You've got here method Notepad.temizle() AND button Notepad.temizle
So when you expect to send a message, instead you send a button, which is typeError
Also I can see the same error with other methods

AttributeError: 'ExampleApp' object has no attribute 'browse_folder'

from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import ADJ_Search
import os
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import webbrowser
class ExampleApp(QtGui.QMainWindow, ADJ_Search.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.Chose_File_Button.clicked.connect(self.browse_folder)
self.List_Search_Button.clicked.connect(self.search_list)
def browse_folder(self):
self.List_ADJ_View.clear()
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
directory = QStringList()
if dlg.exec_():
directory = dlg.selectedFiles()
f = open(directory[0], 'r')
with f:
data = f.readlines()
for ADJ in data:
self.List_ADJ_View.addItem(ADJ.strip())
print ADJ.strip()
def search_list(self):
self.List_ADJ_View.clear()
print ''
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__=='__main__':
main()
Error:
Error:Traceback (most recent call last):
File "temperary.py", line 45, in <module>
File "temperary.py", line 40, in main
form = ExampleApp()
File "temperary.py", line 15, in __init__
self.Chose_File_Button.clicked.connect(self.browse_folder)
AttributeError: 'ExampleApp' object has no attribute 'browse_folder'
Please help me to see why it always come out this error, also 'search_list' has this kind of error too. What do you think is causing it?

Python timed subprocess.Popen

I have the following code which gets data from a webscrape.
I only just learnt how to use the
subprocess.Popen
and i am trying to ouse my initiative along with other answers to similar questions on how to use the
subprocess.Popen
to execute the script below to get the webscrape data into my insert field updated every 30 seconds or so. But it is not working. Please could you point me in the right direction?
import xlrd
import subprocess
from Tkinter import *
import urllib2
from ttk import *
import Tkinter as tk
class Application(Frame):
"""GUI to display results of 'equity get'"""
def __init__(self, master):
"""initialise the Frame"""
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create button, text and entry Widget"""
"""what it is i.e. label"""
url = "https://......."
request= urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<.......">", 1);
splitted_page = splitted_page24[1].split("</.......>", 1)
self.data = Label(self, text ="Data")
self.data1 = Entry(self, width = 10)
self.data1.insert(0,splitted_page[0])
self.data.grid(column = 1, row = 1)
self.data1.grid(column = 2, row = 1)
self.data1.grid(column = 3, row = 1)
a = 0
while a < 10:
a += 1
time.sleep(15)
while True:
out = subprocess.Popen(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
app = Application(root)
root.title("reload test")
root.geometry("700x300")
root.mainloop()
the error i get is
error no 22: invalid syntax referring to the script between the
(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
then multiple command line windows open displaying the same error and i have to shut down the computer to stop it!
i amended the reference to my file with the 'r' prefix as follows:
([r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
but removed the python.exe call as it just calling up the command line window. Now, i receive the following error message:
Traceback (most recent call last):
File "C:\Users\....\Desktop\Py\Python27\.....\tester.py", line 46, in <module>
app = Application(root)
File "C:\Users\......\Desktop\Py\Python27\.....\tester.py", line 18, in __init__
self.create_widgets()
File "C:\Users\.....\Desktop\Py\Python27\......\tester.py", line 44, in create_widgets
out = subprocess.Popen([r"C:\Users\Isaac\Desktop\Py\Python27\.....\tester.py"])
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 672, in __init__
errread, errwrite)
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 882, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
Python uses backslash to quote characters, like \n = newline and \t = tab.
Use an r prefix to make a raw string literal, like a Windows file path:
out = subprocess.Popen([r"C:\Users\.....\Desktop\Py\python.exe", r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])

Categories

Resources