This question already has answers here:
'google-cloud-firestore' distribution doesn't get added to PyInstaller build
(3 answers)
Closed 3 years ago.
I am using a lot of dependencies for my python project. I am using firestore, pyqt5, numpy and some others. I tried creating an executable file using Pyinstaller but whenever I run the file it says "failed to execute script.
Also I am using images folder and 2 other python file as imports in my main.py file
I tried using hidden imports and still wouldn't work. Is there any easy way to create a pyqt5+firestore project?
Main.py
from PyQt5 import QtWidgets
from HomePage import Ui_HomePage
from attendance import Ui_Dialog
class Firstwindow(QtWidgets.QMainWindow, Ui_HomePage):
def __init__(self, parent=None):
super(Firstwindow, self).__init__(parent)
self.setupUi(self)
self.viewAttendance.clicked.connect(self.hide)
class Secondwindow(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Secondwindow, self).__init__(parent)
self.setupUi(self)
self.backButton.clicked.connect(self.hide)
class Manager:
def __init__(self):
self.first = Firstwindow()
self.second = Secondwindow()
self.first.viewAttendance.clicked.connect(self.second.show)
self.second.backButton.clicked.connect(self.first.show)
self.first.show()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
manager = Manager()
sys.exit(app.exec_())
attendance.py
from PyQt5 import QtCore, QtGui, QtWidgets
import firebase_admin
import google.cloud
from firebase_admin import credentials, firestore
cred = credentials.Certificate("******")
app1 = firebase_admin.initialize_app(cred)
"""Creating a database and authorization object"""
DB = firestore.client()
ids = []
names = []
age = []
job = []
phone = []
year = []
date = []
shiftStart = []
shiftEnd = []
store = firestore.client()
peopleRef = store.collection(u'People')
salaryRef = store.collection('Salary')
jobRef = store.collection('Jobs')
recordRef = store.collection('Records')
dates = recordRef.stream()
for dat in dates:
x = store.collection('Records').document(dat.id).collection('Present')
idx = x.stream()
for i in idx:
print(i.id)
print(i.to_dict()['Name'])
jo = jobRef.stream()
for doc in jo:
fo = doc.id
print(fo)
def getData():
try:
docs = peopleRef.stream()
for doc in docs:
ids.append(doc.id)
names.append(doc.to_dict()['Name'])
job.append(doc.to_dict()['Age'])
age.append(doc.to_dict()['Job Type'])
phone.append(doc.to_dict()['Phone'])
except google.cloud.exceptions.NotFound:
print(u'Missing data')
return ids,names,job,age,phone
def clearData():
ids.clear()
names.clear()
age.clear()
job.clear()
phone.clear()
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(595, 337)
Dialog.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False)
self.gridLayout_2 = QtWidgets.QGridLayout(Dialog)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 5, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem1, 0, 3, 1, 1)
self.dateEdit = QtWidgets.QDateEdit(Dialog)
self.dateEdit.setStyleSheet("font: 10pt \"Verdana\";")
self.dateEdit.setObjectName("dateEdit")
self.gridLayout.addWidget(self.dateEdit, 0, 6, 1, 1)
self.refreshButton = QtWidgets.QPushButton(Dialog)
self.refreshButton.setStyleSheet("qproperty-icon:url(:/images/icons/refresh.png);\n"
"background-color: rgb(255, 255, 255);")
self.refreshButton.setText("")
self.refreshButton.setIconSize(QtCore.QSize(20, 20))
self.refreshButton.setFlat(False)
self.refreshButton.setObjectName("refreshButton")
self.gridLayout.addWidget(self.refreshButton, 0, 4, 1, 1)
self.searchDate = QtWidgets.QPushButton(Dialog)
self.searchDate.setStyleSheet("QPushButton {\n"
" color: rgb(0,0,0);\n"
" border: 2px solid #555;\n"
" border-radius: 20px;\n"
" border-style: outset;\n"
" background: rgb(215, 252, 255);\n"
" padding: 5px;\n"
" font: 75 8pt \"Georgia\";\n"
" }\n"
"\n"
"QPushButton:hover {\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"\n"
"QPushButton:pressed {\n"
" border-style: inset;\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"")
self.searchDate.setObjectName("searchDate")
self.gridLayout.addWidget(self.searchDate, 0, 7, 1, 1)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.backButton = QtWidgets.QPushButton(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.backButton.sizePolicy().hasHeightForWidth())
self.backButton.setSizePolicy(sizePolicy)
self.backButton.setStyleSheet("qproperty-icon:url(:/images/icons/back.jpg);\n"
"background-color: rgb(255, 255, 255);")
self.backButton.setText("")
self.backButton.setObjectName("backButton")
self.horizontalLayout.addWidget(self.backButton)
self.nameEntry = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.nameEntry.sizePolicy().hasHeightForWidth())
self.nameEntry.setSizePolicy(sizePolicy)
self.nameEntry.setStyleSheet("font: 10pt \"Verdana\";")
self.nameEntry.setObjectName("nameEntry")
self.horizontalLayout.addWidget(self.nameEntry)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.searchName = QtWidgets.QPushButton(Dialog)
self.searchName.setStyleSheet("QPushButton {\n"
" color: rgb(0,0,0);\n"
" border: 2px solid #555;\n"
" border-radius: 20px;\n"
" border-style: outset;\n"
" background: rgb(215, 252, 255);\n"
" padding: 5px;\n"
" font: 75 8pt \"Georgia\";\n"
" }\n"
"\n"
"QPushButton:hover {\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"\n"
"QPushButton:pressed {\n"
" border-style: inset;\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"")
self.searchName.setObjectName("searchName")
self.gridLayout.addWidget(self.searchName, 0, 1, 1, 1)
self.profileTree = QtWidgets.QTableWidget(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.profileTree.sizePolicy().hasHeightForWidth())
self.profileTree.setSizePolicy(sizePolicy)
self.profileTree.setObjectName("profileTree")
self.gridLayout.addWidget(self.profileTree, 1, 0, 1, 1)
self.dataTree = QtWidgets.QTableWidget(Dialog)
self.dataTree.setObjectName("dataTree")
self.gridLayout.addWidget(self.dataTree, 1, 1, 1, 7)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.dataTree.setColumnCount(0)
self.dataTree.setRowCount(0)
self.profileTree.setRowCount(0)
self.profileTree.setColumnCount(0)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.profileTree.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
self.refreshButton.clicked.connect(self.refresh)
self.profileTree.cellDoubleClicked.connect(self.showClicked)
def showClicked(self,row,col):
idx = self.profileTree.item(row,0).text()
print(idx)
def refresh(self):
profileData = getData()
self.profileTree.setRowCount(len(profileData[0]))
self.profileTree.setColumnCount(2)
self.profileTree.setHorizontalHeaderLabels(('ID', 'Name'))
for row in range(len(profileData[0])):
for col in range(2):
self.profileTree.setItem(row,col,QtWidgets.QTableWidgetItem(profileData[col][row]))
clearData()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.searchDate.setText(_translate("Dialog", "Search"))
self.searchName.setText(_translate("Dialog", "Search"))
import images
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
Ok so after hours of research I found this post - 'google-cloud-firestore' distribution doesn't get added to PyInstaller build
The problem was with firestore and not PyQt.
Related
My code:
import pandas
import requests
from bs4 import BeautifulSoup
from pywebio.input import *
from pywebio.output import *
from time import sleep
from pywebio import start_server
print("News web application successfully started!")
def app():
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
#put_html('<table border="1" width="100%" cellpadding="5">')
source = find.find_all('a', {'data-n-tid' : '9'})
time = find.find_all('time')
textoutput = []
textoutput1 = []
textoutput2 = []
takeoutput3 = []
#writer = open('news.csv', 'w')
#writer1 = csv.writer(writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for text in h3:
a1 = text.text
textoutput.append(a1)
for text2 in source:
a3 = text2.text
textoutput1.append(a3)
for text1 in time:
a5 = text1.text
textoutput2.append(a5)
#for result in link:
# alinks = result.find_all('a')
# alinks1 = []
# for alinks1 in alinks:
# alinks2 = alinks1.get('href')
# alinksreplace = str(alinks2)
# alinksreplace1 = alinksreplace.replace(".", "")
# alinksreplace2 = alinksreplace1.replace("None", "")
#
# if (alinksreplace2 != ''):
# if "publications" not in alinksreplace2:
# a = "https://news.google.com" + alinksreplace2
# takeoutput3.append(a)
pandas.set_option('display.max_colwidth', None)
frame = {'Title':textoutput, 'Time':textoutput2, 'Source' : textoutput1}
frame1 = pandas.DataFrame(frame)
#frame2 = {'Link' : takeoutput3}
#frame3 = pandas.DataFrame(frame2)
frametostring = frame1.to_string(index=False)
#frametostring1 = frame3.to_string(index=False)
#print(frametostring)
put_code(frametostring)
#put_code(frametostring1)
#writer1.writerow([textoutput, textoutput1, textoutput2])
start_server(app, 82)
it worked fine but today Google update something and now it don't start. And it's because Google add before you continue pop-up. How I can bypass this so my script continue to work?
If it was Selenium I've just clicked the button but here I don't know what to do
Thanks you helping!
I am working on creating a graph using GraphStream in Scala.
A small verison of the code is the following :
val graph = new SingleGraph("Tutorial 1")
graph.addNode("A")
graph.addNode("B")
graph.addNode("C")
graph.addEdge("AB", "A", "B")
graph.addEdge("BC", "B", "C")
graph.addEdge("CA", "C", "A")
System.setProperty("org.graphstream.ui", "swing")
graph.display
This code gives the following result :
I've looked in the official documentation of GraphStream but I couldn't find how to make the Ids of Nodes and Edges appear. So my question is, how can I add text to my graph ?
You can specify this in the CSS stylesheet of the graphstream. Simply use text-mode: normal. Stylesheet can be set by graph.setAttribute("ui.stylesheet", myStyleSheet)
Example from my stylesheet:
node{
size: 10px, 10px;
shape: circle;
fill-color: #B1DFF7;
stroke-mode: plain;
stroke-color: #B1DFF7;
stroke-width: 3;
text-mode: normal; /*normal or hidden*/
text-background-mode: plain; /*plain or none*/
text-background-color: rgba(255, 255, 255, 200);
text-alignment: above;
}
Here you are
System.setProperty("org.graphstream.ui", "swing");
var graph = new SingleGraph("Tutorial 1");
graph.setAttribute("ui.stylesheet", "node{\n" +
" size: 30px, 30px;\n" +
" fill-color: #f7f7f0;\n" +
" text-mode: normal; \n" +
"}");
graph.addNode("A").setAttribute("ui.label", "A");
graph.addNode("B").setAttribute("ui.label", "B");
graph.addNode("C").setAttribute("ui.label", "C");
graph.addEdge("AB", "A", "B").setAttribute("ui.label", "AB");
graph.addEdge("BC", "B", "C");
graph.addEdge("CA", "C", "A");
graph.display();
I have a groupBox in my PyQt5-Application which serves as a dropzone, where the user can upload files and the dropEvent prints a list of the filenames that were dragged into the dropzone and writes them to the listWidget. I have slightly changed the original code from here:
dropfiles.py
# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
import os
from PyQt5 import QtCore, QtGui, QtWidgets
class Drop_groupBox(QtWidgets.QGroupBox):
dropped = QtCore.pyqtSignal(list)
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
list_of_files = [url.toLocalFile() for url in e.mimeData().urls() if os.path.isfile(url.toLocalFile())]
self.dropped.emit(list_of_files)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(658, 449)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(658, 449))
MainWindow.setMaximumSize(QtCore.QSize(658, 449))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_Files = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_Files.sizePolicy().hasHeightForWidth())
self.label_Files.setSizePolicy(sizePolicy)
self.label_Files.setMinimumSize(QtCore.QSize(122, 20))
self.label_Files.setMaximumSize(QtCore.QSize(122, 20))
self.label_Files.setObjectName("label_Files")
self.gridLayout.addWidget(self.label_Files, 0, 0, 1, 1)
self.listWidget_Files = QtWidgets.QListWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.listWidget_Files.sizePolicy().hasHeightForWidth())
self.listWidget_Files.setSizePolicy(sizePolicy)
self.listWidget_Files.setMinimumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setMaximumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setObjectName("listWidget_Files")
self.gridLayout.addWidget(self.listWidget_Files, 1, 0, 1, 1)
self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1)
# self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox = Drop_groupBox(self.centralwidget)
self.groupBox.dropped.connect(self.fill_fileslist)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(300, 300))
self.groupBox.setMaximumSize(QtCore.QSize(400, 300))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_3.addWidget(self.groupBox, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 658, 19))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "TestCase"))
self.label_Files.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">Selected Files</span></p></body></html>"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\">Drop Files Here!</span></p></body></html>"))
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
This works perfectly fine, when I have all the code in one file. But now my problem is that I am designing a gui with the PyQt Designer and I want to separate the "gui"-file from the file with the programming logic (programming functions), so that when I change something in the gui and convert it to a python file (with pyuic), the functions not defined in the Designer won't be overwritten. So this is what I have tried:
mainwindow.py (the gui file)
# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(658, 449)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(658, 449))
MainWindow.setMaximumSize(QtCore.QSize(658, 449))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_Files = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_Files.sizePolicy().hasHeightForWidth())
self.label_Files.setSizePolicy(sizePolicy)
self.label_Files.setMinimumSize(QtCore.QSize(122, 20))
self.label_Files.setMaximumSize(QtCore.QSize(122, 20))
self.label_Files.setObjectName("label_Files")
self.gridLayout.addWidget(self.label_Files, 0, 0, 1, 1)
self.listWidget_Files = QtWidgets.QListWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.listWidget_Files.sizePolicy().hasHeightForWidth())
self.listWidget_Files.setSizePolicy(sizePolicy)
self.listWidget_Files.setMinimumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setMaximumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setObjectName("listWidget_Files")
self.gridLayout.addWidget(self.listWidget_Files, 1, 0, 1, 1)
self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(300, 300))
self.groupBox.setMaximumSize(QtCore.QSize(400, 300))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_3.addWidget(self.groupBox, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 658, 19))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "TestCase"))
self.label_Files.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">Selected Files</span></p></body></html>"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\">Drop Files Here!</span></p></body></html>"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
dropfiles_functions.py (the file with the programming logic)
# -*- coding: utf-8 -*-
import os
from PyQt5 import QtCore, QtWidgets
from dropfiles_gui import Ui_MainWindow
class Drop_groupBox(QtWidgets.QGroupBox):
dropped = QtCore.pyqtSignal(list)
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
list_of_files = [url.toLocalFile() for url in e.mimeData().urls() if os.path.isfile(url.toLocalFile())]
self.dropped.emit(list_of_files)
class MConv(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.groupBox = Drop_groupBox(self.ui.centralwidget) # <-- why is this not working?
self.ui.groupBox.dropped.connect(self.fill_fileslist) # <-- why is this not working?
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MConv()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I don't understand why the drop event is not passed to the groupBox. In the file 'dropfiles_functions.py' I changed the 'self.ui.groupBox' to the 'new Drop_groupBox', but its funcitonaltiy is not working. Can someone please explain to me why this is the case and what I'm doing wrong?
In order to get this to work, you need to promote your groupbox widget in QtDesigner from a QtWidgets.QGroupBox to a Drop_groupBox widget. You can check the official Qt documentation to find out how. If you succeed and convert the .ui file to a .py file, the line
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
should have been replaced by
self.groupBox = Drop_groupBox(self.centralwidget)
and at the bottom of the .py file there should be an import statement similar to
from dropfiles_functions import Drop_groupBox
The next step is to correctly setup MConv. Since MConv inherits from both QMainWindow and Ui_MainWindow, you don't need to create a separate instance of Ui_MainWindow in QMainWindow.__init__. Instead you can refer to MConv.setupUi and MConv.groupBox directly, i.e.
class MConv(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__(self)
self.setupUi(self) # <-- this will define self.groupBox = Drop_groupbox(...) amongst others
self.groupBox.dropped.connect(self.fill_fileslist)
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
Finally, in the if __name__ == "__main__" block you need to make sure you are using an instance of MConv rather than a standard QMainWindow, i.e.
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MConv()
MainWindow.show()
sys.exit(app.exec_())
I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.
it seems my Tkinter GUI is fine however when loaded the buttons which should activate the class methods do nadda.
I was originally trying to initiate a class instance within the main:
if_name_== "main":
ed.EditorUI()
Where 'self' is used below 'ed' was in its place.. it said ed was undefined which prompted me to try this way.
As you can probably tell its been a few years since I've coded.
Your help is much appreciated!
import CU_picture
import filters
import Tkinter
root = Tk()
root.title('Photo Editor Version 1.10')
#root.iconbitmap(bitmap = '12.ico')
#img = PhotoImage(file='12.ico')
#root.tk.call('wm', 'iconphoto', root._w, img)
#Adding File Menu
menubar = Tkinter.Menu(root)
filemenu = Tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
#Display above menus
root.config(menu=menubar)
class EditorUI(object):
def __init__(self):
self.name = "EditorUI"
self.pic = 0
self.pix = CU_picture.Picture()
self.filters = "No Current Filters Applied"
self.special = "cake"
def get_specific_color(color):
if color == "red":
return CU_picture.Color(255, 0, 0)
elif color == "aqua":
return CU_picture.Color(0, 255, 255)
elif color == "fuschia":
return CU_picture.Color(255, 0, 255)
elif color == "lime":
return CU_picture.Color(0, 255, 0)
elif color == "yellow":
return CU_picture.Color(255, 255, 0)
def load():
self.pix = get_picture()
self.pix.show()
self.pic = 1
error.set("Pic Loaded: "+self.filters)
outtext.set("New Picture - Not Saved.")
self.filters = "No Current Filters Applied"
self.special = "cake"
para.set("")
def save():
if self.pic == 0:
error.set("No Pic Loaded")
else:
name = intext.get() + ".jpg"
self.pix.write_to(name)
outtext.set("Saved To Given Filename.")
para.set("")
def negative():
if self.pic == 0:
error.set("No Pic Loaded")
else:
n = filters.NegativeFilter()
n.apply(ed.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def grayscale():
if self.pic == 0:
error.set("No Pic Loaded")
else:
g = filters.GrayScaleFilter()
g.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def posterize():
if self.pic == 0:
error.set("No Pic Loaded")
else:
p = filters.PosterizeFilter()
p.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def highlight():
if self.pic == 0:
error.set("No Pic Loaded")
else:
if intext.get() == "":
para.set("Input Highlight distance/Colour and try again(one at a time).")
elif self.special == "cake" and intext.get() != "":
self.special = intext.get()
outtext.set("Highlight distance: " + self.special)
para.set("Input Highlight colour(red, blue, aqua, fuschia, lime, yellow) for the final step.")
elif self.special != "cake" and intext.get() != "":
color = get_specific_color(intext.get())
h = filters.HighlightFilter()
h.set_distance(float(self.special))
h.set_color(color)
outtext.set("Highlight colour: " + intext.get())
h.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def edge():
if self.pic == 0:
error.set("No Pic Loaded")
else:
para.set("Threshold?")
if intext.get() == "":
para.set("Input Threshold value and try again.")
else:
para.set("Threshold: " + intext.get())
e = filters.EdgeFilter()
e.set_threshold(float(intext.get()))
e.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def get_picture():
"""
Interactively select a picture file and return it.
"""
# Pop up a dialogue box to select a file
file = CU_picture.pick_a_file()
# Open the file containing the picture and load it
pict = CU_picture.load_picture(file)
return pict
if __name__ == "__main__":
EditorUI()
intext = Tkinter.StringVar()
outtext = Tkinter.StringVar()
error = Tkinter.StringVar()
para = Tkinter.StringVar()
inp = Tkinter.Entry(root, textvariable=intext)
out = Tkinter.Label(root, textvariable=outtext)
ER = Tkinter.Label(root, textvariable=error)
P = Tkinter.Label(root, textvariable=para)
load = Tkinter.Button(root, text="Load", height=2, width=20, command=load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=edge)
inp.grid(row=1, column=7)
ER.grid(row=0, column= 0, columnspan=5, rowspan=2)
out.grid(row=1, column= 0, columnspan=5, rowspan=2)
P.grid(row=2, column= 0, columnspan=5, rowspan=2)
load.grid(row=0, column=6)
save.grid(row=0, column=7)
negative.grid(row=1, column=6)
grayscale.grid(row=3, column=7)
posterize.grid(row=3, column=6)
highlight.grid(row=2, column=6)
edge.grid(row=2, column=7)
root.mainloop()
One of the main problems that I see (other than what #A.Rodas mentioned above) that would prevent the buttons from doing anything is that your button commands are not actually targeting the class methods. They're looking for root-level callables named "load", "save", etc. Because these don't exist, you should be getting errors, and yet you say the interface works fine aside from the buttons not cooperating, which doesn't make sense to me.
To call the class methods, you must create an instance of the class. First fix the self issue mentioned by #A.Rodas above, then replace the __main__ check with this:
editor = EditorUI()
Then modify the button commands to call the methods on the editor instance:
load = Tkinter.Button(root, text="Load", height=2, width=20, command=editor.load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=editor.save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=editor.negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=editor.grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=editor.posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=editor.highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=editor.edge)
You may also consider moving all the interface creation stuff inside the EditorUI class, unless you have some other reason for keeping it separate.