我对PyQt5和Pyinstaller非常陌生。
我遵循了本教程(https://www.youtube.com/watch?v=mBvpoNLb654&list=PLuTktZ8WcEGTdId-Kjbj6gsZTk65yudJh),并使用QT Designer设计了一个.ui文件,并编写了Python脚本来创建一个小型系统,该系统可以在Jupyter Notebook上运行时正常工作。然后,我将系统转换为一个文件,该文件可以使用auto-py-to-exe(基于Pyinstaller)执行。
我想导出为一个文件,隐藏控制台,并添加其他文件(.ui文件)以及.py脚本。它使用的命令如下:
pyinstaller -y -F -w --add-data "C:/Users/user/Desktop/PyQt5/Marketing_Management_System.ui";"." "C:/Users/user/Desktop/PyQt5/Marketing_Management_System_v1.0.py"
系统已成功导出。但是,当我尝试打开可执行文件时,它会弹出一个错误:
Fatal Error! Failed to execute script <my script name>
下面是我的.py脚本的代码:
import os
import sys
import sqlite3
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import *
class SqliteHelper:
def __init__(self, name=None):
self.conn = None
self.cursor = None
if name:
self.open(name)
def open(self, name):
try:
self.conn = sqlite3.connect(name)
self.cursor = self.conn.cursor()
print ("Connected to database.")
except sqlite3.Error as e:
print ("Fail in connecting to database.")
def edit(self, query, inserts): # INSERT, UPDATE
c = self.cursor
c.execute(query, inserts)
self.conn.commit()
def select(self, query, where_clause): # SELECT
c = self.cursor
c.execute(query, where_clause)
rows = c.fetchall()
return rows
def addUser():
first_name = dlg.first_name_input.text()
last_name = dlg.last_name_input.text()
gender = dlg.gender_input.currentText()
phone_no = dlg.phone_no_input.text()
date = dlg.contact_calendar.selectedDate().toString("yyyy-MM-dd")
remark = dlg.remark_input.text()
if first_name == "" or last_name == "" or gender == "" or phone_no == "": # Check if all inputs are typed in
QMessageBox.information(None, "Something missing...", "Please make sure if all inputs are typed in. You may leave remark as blank.")
else:
new_contact = (first_name, last_name, gender, phone_no, date, remark)
helper.edit("INSERT INTO Parents_Contact (First_Name, Last_Name, Gender, Phone_No, Date, Remark) VALUES (?, ?, ?, ?, ?, ?)", new_contact)
# After adding user, display message
QMessageBox.information(None, "Successful", "Data input successfully.")
# Remove user input after record inserted to db
dlg.first_name_input.setText("")
dlg.last_name_input.setText("")
dlg.gender_input.clear()
dlg.gender_input.addItems(["Female", "Male"])
dlg.phone_no_input.setText("")
dlg.remark_input.setText("")
def searchUser():
dlg.search_table.setRowCount(0) # Remove previous result
search_input = dlg.search_input.text()
if search_input == "": # to prevent wrong logic of not entering text and display all search result - even out of date range result will be displayed when if statement doesn't exist.
QMessageBox.information(None, "Type to search", "Please enter text to search.")
else:
left_calendar = dlg.left_calendar.selectedDate() # by default it's selected as Aug 20 (start of school year)
right_calendar = dlg.right_calendar.selectedDate()# by default it's selected as today's date
search_input_tuple = (left_calendar.toString("yyyy-MM-dd"), right_calendar.toString("yyyy-MM-dd"), search_input.lower(), search_input.lower(), search_input.lower())
rows = helper.select("SELECT * FROM Parents_Contact WHERE (date BETWEEN strftime('%Y-%m-%d',?) AND strftime('%Y-%m-%d',?) AND first_name LIKE ? || '%' OR last_name LIKE ? || '%' or phone_no LIKE ? || '%')", search_input_tuple)
if rows == []: # if returning empty list, which means no record, show messagebox that no record is found
QMessageBox.information(None, "No record", "No record found.")
else:
for row_index, row in enumerate(rows):
dlg.search_table.insertRow(row_index)
for col_index, col in enumerate(row):
if col_index == 0: # Not showing auto increment ID
pass
else:
dlg.search_table.setItem(row_index, col_index - 1, QtWidgets.QTableWidgetItem(str(col)))
app = QtWidgets.QApplication([])
dlg = uic.loadUi("C://Users//user//Desktop//PyQt5//Marketing_Management_System.ui")
helper = SqliteHelper("C://Users//user//Desktop//PyQt5//Marketing_Management_System.db")
dlg.gender_input.addItems(["Female", "Male"])
# Set New_Contact page as default
dlg.tabWidget.setCurrentIndex(0)
dlg.first_name_input.setFocus()
dlg.search_table.setHorizontalHeaderLabels(["First Name", "Last Name", "Gender", "Phone No.", "Date", "Remark"])
dlg.search_table.setEditTriggers(QAbstractItemView.NoEditTriggers) # Not editable
dlg.search_table.setSortingEnabled(True) # sorting by clicking a column
# Stretch the columns in "Search"
header = dlg.search_table.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
# Triggering Submit in "New_Contact"
dlg.submit.clicked.connect(addUser)
dlg.phone_no_input.returnPressed.connect(addUser)
dlg.remark_input.returnPressed.connect(addUser)
# Triggering Search in "Search"
dlg.search.clicked.connect(searchUser)
dlg.search_input.returnPressed.connect(searchUser)
dlg.show()
app.exec()