Open File Dialog running twice repeatedly - python

I tried to open two different types of files with QFileDialog in PyQt5 for pandas dataframe but it open repeatedly twice for each files before executed. However, when I'm using specific file only 'filename' it will directly executed once.
It's opened twice using this code:
class dataframe(QWidget):
def __init__(self, parent=None):
super(dataframe, self).__init__(parent)
layout = QVBoxLayout(self)
canvas = mycanvas(self)
layout.addWidget(canvas)
self.btn3 = QPushButton("Plot")
self.btn3.clicked.connect(canvas.PlotChart)
layout.addWidget(self.btn3)
def input(self):
lasdata = QFileDialog.getOpenFileName(self, 'Open LAS', r'data/', "LAS files (*.las)")[0]
textdata = QFileDialog.getOpenFileName(self, 'Open Text', r'data/', "Text files (*.txt)")[0]
l = lasio.read(f"{lasdata}")
data = l.df()
data = data.replace('-999.00000', np.nan)
data.index.names = ['DEPT']
w = l.well.WELL.value
data['WELL'] = w
text = pd.read_csv(f"{textdata}", sep='\t')
text_unit = text['RU'].unique()
data_w = pd.DataFrame()
for i in range(len(text_unit)):
top = text.iloc[i]['D']
if i < len(text_unit) - 1:
bottom = text.iloc[i + 1]['D']
else:
bottom = int(round(data.tail(1).index.item()))
data_int = data.iloc[top:bottom, :]
data_int['INT'] = text.iloc[i]['RU']
data_w = data_w.append(data_int)
data = data_w
return w, data
def det(self, gr):
w, data = dataframe.input(self)
GR = data.iloc[:, gr]
conditions = [
(GR <= 60),
(GR >= 60)]
lit = ['A', 'B']
data['L'] = np.select(conditions, lit, default='Undefined')
return data
def calculation(self):
w, data = dataframe.input(self)
data = dataframe.det(self, 1)
data_well = pd.DataFrame()
data_int = pd.DataFrame()
F_w = pd.DataFrame()
Fa = pd.DataFrame()
text_unit = data['INT'].unique()
for i in range(len(text_unit)):
data_int = data.where(data['INT'] == text_unit[i]).dropna()
F_percent = data_int['L'].value_counts(normalize=True) * 100
F_percent = F_percent.sort_index()
F_percent['INT'] = text_unit[i]
F_percent = pd.DataFrame(F_percent).transpose()
F_w = F_w.append(F_percent)
F_w['W'] = w
Fa = Fa.append(F_w)
F_w = pd.DataFrame()
Fa = Fa.reset_index()
Fa = Fa.fillna(0)
return Fa
class mycanvas(FigureCanvas):
def __init__(self, parent=None, dpi=120):
self.fig = plt.Figure(dpi=dpi)
FigureCanvas.__init__(self, self.fig)
def PlotChart(self):
outputs = dataframe.calculation(self) # .where(Fa['W']==well)
int = outputs['INT'].unique()
self.axes = self.fig.add_subplot(111)
self.axes.set_title("AA")
outputs.plot.barh(x='INT', stacked=True, ax=self.axes)
self.axes.set_yticks(range(len('INT')), 'INT')
self.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = dataframe()
window.show()
sys.exit(app.exec_())
However, it's directly executed once with this code:
def Input(self):
lasdata = 'data/AA.las'
textdata = 'data/AATEXT.txt'
l = lasio.read(lasdata)
data = l.df()
text = pd.read_csv(textdata, sep='\t')
Is there something wrong with File Dialog code, as with the lower code (direct name) it successfully executed once, but with the file dialog it opened twice before read the next codes. I need to make the GUI app so I need to use the file dialog.
This is part of the code with the two buttons:
self.btn1 = QPushButton("LAS File")
self.btn1.clicked.connect(self.las)
self.btn2 = QPushButton("Text File")
self.btn2.clicked.connect(self.text)
self.btn3 = QPushButton("Plot")
self.btn3.clicked.connect(canvas.PlotChart)
layout.addWidget(self.btn1)
layout.addWidget(self.btn2)
layout.addWidget(self.btn3)
def las(self):
self.lasfile = QFileDialog.getOpenFileName(self, 'Open LAS', r'data/', "LAS files (*.las)")[0]
def text(self):
self.textfile = QFileDialog.getOpenFileName(self, 'Open Text', r'data/', "Text files (*.txt)")[0]
def input(self):
lasdata = self.lasfile
textdata = self.textfile
l = lasio.read(f"{lasdata}")
data = l.df()
data = data.replace('-999.00000', np.nan)
data.index.names = ['DEPT']
w = l.well.WELL.value
data['WELL'] = w
text = pd.read_csv(f"{textdata}", sep='\t')
text_unit = text['RU'].unique()
I try to make it into two buttons but it can't be opened or exit fail to be executed.
below is one of the text format
WN RU D
AA SR 19
AA TF 50
AA PSU 1700

Related

how to turn a python file to exe file with cv2 imported

hi i have a problem where my code is turned into a executable file a error message will appear on the screen does any one know how to fix this error this is for some body tracking software the really cause of this is cv2 but i need some help to make this a executable file so no error messages appeare when opened Many Thanks Jacob PLEASE HELO
[1]: https://i.stack.imgur.com/LKJ5r.png
import cv2
import mediapipe as mp
import pandas as pd
from ast import literal_eval
from tkinter import *
from tkinter import filedialog
import numpy
root = Tk()
#create lebel widget
ScreenLabel = Label(root, text="Body tracking")
#put on screen
root.geometry("500x450+700+200")
#def open():
#global track
#track = filedialog.askopenfilename(initialdir="/dowloads", title="select A File", filetypes=([("all files","*.*")]))
e = Entry(root, width=100)
e.pack()
def tracking():
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
video_file_path = e.get()
cap = cv2.VideoCapture(video_file_path)
coordinates_list = []
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
size = (frame_width, frame_height)
fps = 30
v_split = video_file_path.split(".")
v_split[-2] = v_split[-2] + "_processed"
prep_vid_file_path = ".".join(v_split)
video_saver = cv2.VideoWriter(prep_vid_file_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
keypoints_list = ['CENTER_HEAD',
'LEFT_SHOULDER',
'RIGHT_SHOULDER',
'LEFT_ELBOW',
'RIGHT_ELBOW',
'LEFT_WRIST',
'RIGHT_WRIST',
'LEFT_PINKY',
'RIGHT_PINKY',
'LEFT_INDEX',
'RIGHT_INDEX',
'LEFT_THUMB',
'RIGHT_THUMB',
'LEFT_HIP',
'RIGHT_HIP',
'LEFT_KNEE',
'RIGHT_KNEE',
'LEFT_ANKLE',
'RIGHT_ANKLE',
'LEFT_HEEL',
'RIGHT_HEEL',
'LEFT_FOOT_INDEX',
'RIGHT_FOOT_INDEX']
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
while True:
ret, frame = cap.read()
if ret == False:
cap.release()
video_saver.release()
cv2.destroyAllWindows()
break
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image.flags.writeable = False
results = pose.process(image)
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
timestamp_name = str(cap.get(cv2.CAP_PROP_POS_MSEC))
try:
landmarks = results.pose_landmarks.landmark
CENTER_HEAD = (landmarks[mp_pose.PoseLandmark.NOSE.value].x, landmarks[mp_pose.PoseLandmark.NOSE.value].y, landmarks[mp_pose.PoseLandmark.NOSE.value].z)
LEFT_SHOULDER = (landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].z)
RIGHT_SHOULDER = (landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].z)
LEFT_ELBOW = (landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].z)
RIGHT_ELBOW = (landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].z)
LEFT_WRIST = (landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].z)
RIGHT_WRIST = (landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].z)
LEFT_PINKY = (landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].x, landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].y, landmarks[mp_pose.PoseLandmark.LEFT_PINKY.value].z)
RIGHT_PINKY = (landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_PINKY.value].z)
LEFT_INDEX = (landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.LEFT_INDEX.value].z)
RIGHT_INDEX = (landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_INDEX.value].z)
LEFT_THUMB = (landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].x, landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].y, landmarks[mp_pose.PoseLandmark.LEFT_THUMB.value].z)
RIGHT_THUMB = (landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_THUMB.value].z)
LEFT_HIP = (landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x, landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y, landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].z)
RIGHT_HIP = (landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].z)
LEFT_KNEE = (landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].x, landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y, landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].z)
RIGHT_KNEE = (landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value].z)
LEFT_ANKLE = (landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y, landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].z)
RIGHT_ANKLE = (landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value].z)
LEFT_HEEL = (landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].x, landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].y, landmarks[mp_pose.PoseLandmark.LEFT_HEEL.value].z)
RIGHT_HEEL = (landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_HEEL.value].z)
LEFT_FOOT_INDEX = (landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.LEFT_FOOT_INDEX.value].z)
RIGHT_FOOT_INDEX = (landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].y, landmarks[mp_pose.PoseLandmark.RIGHT_FOOT_INDEX.value].z)
coordinates_list.append(str(timestamp_name) + " : " + str({'CENTER_HEAD':CENTER_HEAD,
'LEFT_SHOULDER':LEFT_SHOULDER,
'RIGHT_SHOULDER':RIGHT_SHOULDER,
'LEFT_ELBOW':LEFT_ELBOW,
'RIGHT_ELBOW':RIGHT_ELBOW,
'LEFT_WRIST':LEFT_WRIST,
'RIGHT_WRIST':RIGHT_WRIST,
'LEFT_PINKY':LEFT_PINKY,
'RIGHT_PINKY':RIGHT_PINKY,
'LEFT_INDEX':LEFT_INDEX,
'RIGHT_INDEX':RIGHT_INDEX,
'LEFT_THUMB':LEFT_THUMB,
'RIGHT_THUMB':RIGHT_THUMB,
'LEFT_HIP':LEFT_HIP,
'RIGHT_HIP':RIGHT_HIP,
'LEFT_KNEE':LEFT_KNEE,
'RIGHT_KNEE':RIGHT_KNEE,
'LEFT_ANKLE':LEFT_ANKLE,
'RIGHT_ANKLE':RIGHT_ANKLE,
'LEFT_HEEL':LEFT_HEEL,
'RIGHT_HEEL':RIGHT_HEEL,
'LEFT_FOOT_INDEX':LEFT_FOOT_INDEX,
'RIGHT_FOOT_INDEX':RIGHT_FOOT_INDEX}))
except:
pass
mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
video_saver.write(image)
cv2.imshow("Video Feed", image)
cv2.waitKey(1)
v_split = video_file_path.split(".")
v_split[-1] = "txt"
v_split[-2] = v_split[-2] + "_coordinates"
coordinates_file_path = ".".join(v_split)
with open(coordinates_file_path, "w") as f:
f.write("\n".join(coordinates_list))
v_split = video_file_path.split(".")
v_split[-1] = "xlsx"
v_split[-2] = v_split[-2] + "_excel"
coordinates_excel_path = ".".join(v_split)
def get_vals(x):
vals = []
for i in x:
for j in i:
vals.append(j)
return vals
df = pd.DataFrame(coordinates_list)
df["frame"] = df[0].apply(lambda x: x.split(" : ")[0])
df[0] = df[0].apply(lambda x: get_vals(literal_eval(x.split(" : ")[1]).values()))
df_columns = []
mapper_dict = {0:"x", 1:"y", 2:"z"}
for keypoint in keypoints_list:
for i in range(0,3):
df_columns.append(keypoint+"_"+mapper_dict.get(i))
df = pd.concat([df["frame"], pd.DataFrame(df[0].to_list(), columns=df_columns)], axis=1)
df.to_excel(coordinates_excel_path, index=False)
#open_btn = Button( root, text="open File", command=open, borderwidth=0).pack()
ExportButton = Button(root, text="Track", command=tracking ,borderwidth=0 ,fg="blue")
ExportButton.pack()
root.mainloop()

How to show text variable in the Tkinter window?

I'm working on thermography camera and i making the interface. I face some error that my textvariable won't print in the tkinter but still can be printed on the shell. What is wrong with my code?
import pandas as pd
import cv2
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.filedialog import askopenfilenames
# List of list
images = []
gs = []
B = []
G = []
R = []
suhu = []
suhuo = []
red = []
green = []
blue = []
waktu = []
utama = Tk()
# Fungsi-fungsi
def mouseRGB(event,x,y,flags,param):
global gambar
if event == cv2.EVENT_LBUTTONDOWN:
colorsB = gambar[y,x,0]
colorsG = gambar[y,x,1]
colorsR = gambar[y,x,2]
R.append(colorsR)
G.append(colorsG)
B.append(colorsB)
def Tutup ():
utama.destroy()
def tolong ():
messagebox.showinfo('Help','Jika terjadi error atau kesulitan dalam menggunakan program ini dapat menghubungi 08111903747')
def loadImages ():
global wkt
global gambar
global tem
wkt = float(wktu.get())
Gambar = askopenfilenames(parent=jwaktu,
title='Select a thermal image file',
filetypes=[('JPG File','*.jpg'),
('PNG File','*.png'),
('All Files','*')])
# Tutorial pake aplikasi
messagebox.showinfo('How to use','After clicking or dragging the selected picture, press S for next image')
# Program olah suhu
# Perintah Load gambar ke python
filenames = Gambar
# Jendela Mouse
cv2.namedWindow('mouseRGB')
cv2.setMouseCallback('mouseRGB',mouseRGB)
time = 0
for file in filenames:
gambar = cv2.imread(file)
time += wkt
cv2.imshow('mouseRGB',gambar)
while(1):
if cv2.waitKey(0) & 0xFF == ord('s') :
for r in R:
red.append(float(r))
for g in G:
green.append(float(g))
for b in B:
blue.append(float(b))
nr = [i * 0.020411398053616 for i in red]
ng = [j * -0.01805397732321 for j in green]
nb = [k * -0.06212844019856 for k in blue]
R.clear()
G.clear()
B.clear()
red.clear()
green.clear()
blue.clear()
lum = nr + ng + nb
lumi = sum(lum)
tem = lumi + 34.9927907296913
if tem >= 33.0 and tem<= 39.0:
suhuo.append(tem)
waktu.append(time)
suhu.append([file,time,tem])
SuhuA = Label(jwaktu,textvariable = tem)
SuhuA.grid(column=1, row = 1)
print(tem)
break
cv2.destroyAllWindows()
# Olah grafik
plt.plot(waktu,suhuo)
plt.xlabel('Waktu (s)')
plt.ylabel('Suhu (C)')
plt.title('Sebaran suhu')
plt.savefig('Sebaran_suhu.png')
plt.show()
# Masukan data kedalam csv
img_df = pd.DataFrame(suhu ,columns = ['Image','Waktu','Temperature'])
img_df.to_csv('Olah_Suhu.csv')
waktu.clear()
suhuo.clear()
def TIP ():
global SuhuA
global wktu
global jwaktu
jwaktu = Tk()
jwaktu.title('Thermal Image Processing')
jwaktu.geometry('600x400')
Tulisanw = Label(jwaktu,text='Enter the sampling time : ')
Tulisanw.grid(column = 0 , row = 0)
wktu = Entry(jwaktu,width = 10)
wktu.grid(column = 1, row = 0)
tombolw = Button(jwaktu,text='Execute',command=loadImages)
tombolw.grid(column = 2, row = 0)
Suhu = Label(jwaktu,text='Temperature Point : ')
Suhu.grid(column = 0, row = 1)
jwaktu.mainloop()
return wktu
# Window GUI
utama.title('TCI - Thermograpgy Camera Interface')
utama.geometry('600x400')
menu = Menu(utama)
program = Menu(menu)
program.add_command(label = 'Close',command=Tutup)
menu.add_cascade(label='File', menu=program)
menu.add_command(label = 'Help',command=tolong)
utama.config(menu=menu)
TombolTIP = Button(utama,width=30,text='Thermal Image Processing',command=TIP)
TombolTIP.grid(padx = 200,pady = 50)
TombolRTM = Button(utama,width=30,text = 'Realtime Thermal Measurment')
TombolRTM.grid(padx=200,pady=150)
utama.mainloop()
When i was executing on the other window the temperature point did not show anything. I have already tried to use 'text' instead of 'textvariable', but nothing happened. Thank you for your help!

How to import values from excel with pandas into tkinter faster?

guys! How are you? I have this code below and I'm having this trouble with the insertData function. This function is used to enter values from an excel spreadsheet into the tkinter treeview using Pandas. It's almost all right, but it's too slow and I don't know how to fix it. If anyone could help me, I'd be very happy.
Thanks in advance!
from tkinter import *
import ttk
import openpyxl
import pandas as pd
nuScreen = Tk()
nuScreen.title("ContrasinSystem - Usuário Comum")
nuScreen.iconbitmap("logocontransin.ico")
book = openpyxl.load_workbook('Registros.xlsx')
sheet = book.sheetnames
sh = book.active.cell
#Contador de Linhas:
wb2 = openpyxl.load_workbook('Registros.xlsx')
sheet2 = wb2.worksheets[0]
rowCount = sheet2.max_row
v = []
#Design:
class main():
def __init__(self,tk):
for x in range (0,len(sheet)):
v.append(sheet[int(x)])
self.wb2 = openpyxl.load_workbook('Registros.xlsx')
self.sheet2 = self.wb2.worksheets[0]
self.row_count = self.sheet2.max_row
self.column_count = self.sheet2.max_column
self.nuFrame = Frame(nuScreen, width = 1500, height = 450)
self.nuFrame.pack()
self.img = PhotoImage(file="logocontransin.png")
self.w = Label(self.nuFrame, image = self.img)
self.w.img = self.img
self.w.place(x=65,y=150)
self.srchlbl = ttk.Label(self.nuFrame, text = "Buscar:")
self.srchlbl.place(x=25,y=75)
self.srchetr = ttk.Entry(self.nuFrame, width = 30)
self.srchetr.place(x=75,y=75)
self.treeview = ttk.Treeview(self.nuFrame)
self.treeview.place(x=300,y=75, width = 1100)
dataVector = []
def columnsName():
def Header():
self.columnVector = []
self.dataVector = []
teste = []
self.treeview.column("#0", width = 20)
self.columnHeader = pd.read_excel(r'Registros.xlsx', str(self.cmb.get()), header_only = True, nrows=0).columns
for a in self.columnHeader:
self.columnVector.append(a)
self.treeview.configure(columns = self.columnVector)
for b in self.columnHeader:
self.treeview.heading(str(b), text = str(b))
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()), skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Header()
insertData()
self.cmbLbl = ttk.Label(self.nuFrame, text = "Assunto:")
self.cmbLbl.place(x=1200, y=325)
self.cmb = ttk.Combobox(self.nuFrame, values = v)
self.cmb.place(x=1250,y=325)
self.btncmb = ttk.Button(self.nuFrame, text = "Buscar", command = columnsName)
self.btncmb.place(x=1320,y=375)
nuScreen.geometry("1500x450")
main(nuScreen)
nuScreen.mainloop()
How many times do you want to open a excel file for reading?
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Should you instead omit the first loop?
def insertData():
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
self.treeview.insert("", "end",values = l)
print(self.dataValues)

Setting a scrollbar to work with a treeview

I'm attempting to add a scrollbar to a tree here in order to keep the data within view for the user, as the tree stretches offscreen(the window is limited at 1280x720). However, the scrollbar does not move it across. Here is the code:
self.treeFrame = ttk.Frame(self)
self.treeFrame.grid(row = 12,column = 0,columnspan = 1000,rowspan = 100)
self.tree = ttk.Treeview(self.treeFrame,height = 100, columns = ('name','purchaseprice','previousprices','listingprice','buyingformat','postage','fees','potprofit','offers','viewcount','sold','offertaken','username','dispatch','delivered','returned','relist','feedback'))
self.tree.heading('#0',text = 'saleID',anchor = 'w')
self.tree.heading('name',text = "Item Name",anchor = 'w')
self.tree.heading('purchaseprice',text = "Purchase Price",anchor = 'w')
self.tree.heading('previousprices',text = "Previous Prices",anchor = 'w')
self.tree.heading('listingprice',text = "Listing Price", anchor = 'w')
self.tree.heading('buyingformat',text = "Buying Format",anchor = 'w')
self.tree.heading('postage',text = "Postage",anchor = 'w')
self.tree.heading('fees',text = "Fees",anchor = 'w')
self.tree.heading('potprofit',text = "Potential Profit",anchor = 'w')
self.tree.heading('offers',text = "Best Offer",anchor = 'w')
self.tree.heading('viewcount',text = "Viewcount",anchor = 'w')
self.tree.heading('sold',text = "Sold?",anchor = 'w')
self.tree.heading('offertaken',text = "Offer Taken?",anchor = 'w')
self.tree.heading('username',text = "Username",anchor = 'w')
self.tree.heading('dispatch',text = "Dispatched?",anchor = 'w')
self.tree.heading('delivered',text = "Delivered?",anchor = 'w')
self.tree.heading('returned',text = "Returned?",anchor = 'w')
self.tree.heading('relist',text = "Relisted?",anchor = 'w')
self.tree.heading('feedback',text = "Feedback",anchor = 'w')
hsb = ttk.Scrollbar(self,orient = "horizontal")
self.tree.grid(row = 14,column = 0,sticky ='nsew')
hsb.grid(row = 11,column = 0,columnspan = 10,sticky = 'ew')
hsb.config(command = self.tree.xview)
Does anyone know how I would go about restricting the size of the tree in order to get it into a position where it can be scrolled across with in the bounds of the window?
Scrollbars need to be told what command to run when the user moves the scrollbar, and widgets need to know which command to run when it has been scrolled. You're not doing either of these.
For example, in your code you need to do both of these:
hsb.configure(command=self.tree.xview)
self.tree.configure(xscrollcommand=hsb.set)

Create a portable version of the desktop app in PyQt5

I have made a UI in QtCreator 5. Then, I converted UI-file "Odor.ui" into "ui-main.py". Then I used Anaconda framework to write a computational part in Upiter Notebook. When, I compile this code
import os
import sys
import pandas as pd
import numpy
import scipy.stats
import xlsxwriter
import re
from PyQt5.QtWidgets import QApplication, QMainWindow, qApp, QWidget, QInputDialog, QLineEdit, QFileDialog, QMessageBox, QTableWidgetItem, QHeaderView
from PyQt5.QtCore import Qt, QEvent, QObject
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtGui
from ui_main import Ui_MainWindow
from os import walk
from os.path import expanduser as ospath
import glob
from time import gmtime, strftime
class MyMainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
qApp.installEventFilter(self)
self.setupUi(self)
self.dataChooseBtn.clicked.connect(self.selectFile)
self.saveSample_btn.clicked.connect(self.saveSample)
self.data_processing.clicked.connect(self.process)
self.string_processing.clicked.connect(self.processString)
self.saveSampleString.clicked.connect(self.saveSampleStr)
self.refreshSample()
self.refreshSamples.clicked.connect(self.refreshSample)
self.refreshSample_2()
self.refreshSamples_2.clicked.connect(self.refreshSample_2)
self.show()
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Escape:
self.close()
return super(MyMainWindow, self).eventFilter(obj, event)
#pyqtSlot()
def accept(self):
textboxValue = self.paramInput_field_2.text()
QMessageBox.information(self, 'Message', "Значения параметрического столбца: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)
def selectFile(self):
self.fileName = None
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"Выберите стандартизированную выборку", "./Unprocessed samples","All Files (*);;Python Files (*.py)", options=options)
if fileName:
self.fileName = fileName
def process(self):
sample_param = pd.read_excel(self.fileName, header = None, sheetname = 1)
param = sample_param[0].tolist()
sample = pd.read_excel(self.fileName, sheetname = 0)
list_of_index = []
for i in range(len(sample.columns)):
sample2 = sample.iloc[:, lambda sample: [i]]
sample2 = sample2.columns[0]
list_of_index.append(sample2)
list_of_index
fulllist = []
for i in list_of_index:
sample3 = sample[i].tolist()
fulllist.append(sample3)
fulllist_percent = []
column_percent = []
len(fulllist)
for i in range(len(fulllist)):
for j in range(len(fulllist[i])):
percent_rank = scipy.stats.percentileofscore(fulllist[i], fulllist[i][j])
column_percent.append(percent_rank)
fulllist_percent.append(column_percent)
column_percent = []
fulllist_rank = []
for i in range(len(fulllist)):
rank = len(fulllist[i]) - scipy.stats.rankdata(fulllist[i]) + 1
fulllist_rank.append(rank)
param_rank = scipy.stats.rankdata(param).astype(int)
column_corr = []
for i in range(len(fulllist)):
correlation = scipy.stats.spearmanr(param_rank[::-1], fulllist_rank[i])
column_corr.append(correlation[0])
fulllist_click = []
for j in range (len(fulllist_percent)):
middle = []
if column_corr[j] > 0:
for i in range(len(fulllist_percent[j])):
solve = column_corr[j] * fulllist_percent[j][i]
middle.append(solve)
else:
for i in range (len(fulllist_percent[j])):
solve = abs(column_corr[j]) * (100 - fulllist_percent[j][i])
middle.append(solve)
fulllist_click.append(middle)
list_of_rowsumm = []
rowsumm = 0
fulllist_clickT = numpy.asarray(fulllist_click).T.tolist()
for i in range(len(fulllist_clickT)):
rowsumm = sum(fulllist_clickT[i])
list_of_rowsumm.append(rowsumm)
percent_rowsumm = []
for i in list_of_rowsumm:
x = scipy.stats.percentileofscore(list_of_rowsumm, i)
percent_rowsumm.append(x)
validity = scipy.stats.pearsonr(list_of_rowsumm, param)
validity = validity[0]
additional_info = []
additional_info.append(list_of_rowsumm)
additional_info.append(percent_rowsumm)
additional_info.append(param)
self.fulllist = fulllist
self.fulllist_percent = fulllist_percent
self.fulllist_click = fulllist_click
self.additional_info = additional_info
self.validity = validity
return self.fulllist, self.fulllist_percent, self.fulllist_click, self.additional_info, self.validity
def saveSample(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileNameSave, _ = QFileDialog.getSaveFileName(self,"Сохранить данные выборки","./Samples","Excel files (*.xlsx)", options=options)
workbook = xlsxwriter.Workbook(fileNameSave + ' ['+ str(round(self.validity, 3)) + ', ' + str(len(self.fulllist)) + ', ' + str(len(self.fulllist[0])) + ']' + ".xlsx")
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()
worksheet3 = workbook.add_worksheet()
worksheet4 = workbook.add_worksheet()
row = 0
for col, data in enumerate(self.fulllist):
worksheet1.write_column(row, col, data)
for col, data in enumerate(self.fulllist_percent):
worksheet2.write_column(row, col, data)
for col, data in enumerate(self.fulllist_click):
worksheet3.write_column(row, col, data)
for col, data in enumerate(self.additional_info):
worksheet4.write_column(row, col, data)
workbook.close()
def processString(self):
check = self.stringInput_field.toPlainText()
check = [float(i) for i in check.replace(',', '.').split()]
index = self.sampleChoose_list.selectedIndexes()[0].row()
sample_path = self.sample_directory[1][index]
sample_param = pd.read_excel(ospath(sample_path), header = None, sheetname = 3)
param = sample_param[2].tolist()
param_rank = scipy.stats.rankdata(param).astype(int)
sample_2 = pd.read_excel(ospath(sample_path), header = None, sheetname = 0)
fulllist_new = []
for i in range(len(sample_2.columns)):
column_new = sample_2[i].tolist()
fulllist_new.append(column_new)
for i in range(len(check)):
fulllist_new[i][0] = check[i]
fulllist_percent_new = []
column_percent_new = []
for i in range(len(fulllist_new)):
for j in range(len(fulllist_new[i])):
percent_rank = scipy.stats.percentileofscore(fulllist_new[i], fulllist_new[i][j])
column_percent_new.append(percent_rank)
fulllist_percent_new.append(column_percent_new)
column_percent_new = []
fulllist_rank_new = []
for i in range(len(fulllist_new)):
rank = len(fulllist_new[i]) - scipy.stats.rankdata(fulllist_new[i]) + 1
fulllist_rank_new.append(rank)
column_corr_new = []
for i in range(len(fulllist_new)):
correlation = scipy.stats.spearmanr(param_rank[::-1], fulllist_rank_new[i])
column_corr_new.append(correlation[0])
fulllist_click_new = []
for j in range (len(fulllist_percent_new)):
middle = []
if column_corr_new[j] > 0:
for i in range(len(fulllist_percent_new[j])):
solve = column_corr_new[j] * fulllist_percent_new[j][i]
middle.append(solve)
else:
for i in range (len(fulllist_percent_new[j])):
solve = abs(column_corr_new[j]) * (100 - fulllist_percent_new[j][i])
middle.append(solve)
fulllist_click_new.append(middle)
check_click = []
for i in range(len(check)):
if column_corr_new[i] > 0:
click = fulllist_percent_new[i][0] * column_corr_new[i]
check_click.append(click)
elif column_corr_new[i] < 0:
click = abs(column_corr_new[i]) * (100 - fulllist_percent_new[i][0])
check_click.append(click)
len(check_click)
list_of_rowsumm_new = []
rowsumm = 0
fulllist_click_newT = numpy.asarray(fulllist_click_new).T.tolist()
for i in range(len(fulllist_click_newT)):
rowsumm = sum(fulllist_click_newT[i])
list_of_rowsumm_new.append(rowsumm)
percent_rowsumm_new = []
for i in list_of_rowsumm_new:
x = scipy.stats.percentileofscore(list_of_rowsumm_new, i)
percent_rowsumm_new.append(x)
validity_new = scipy.stats.pearsonr(list_of_rowsumm_new[1:], param[1:])
validity_new = validity_new[0]
validity_list = []
validity_list.append(validity_new)
additional_info_new = []
additional_info_new.append(list_of_rowsumm_new)
additional_info_new.append(percent_rowsumm_new)
additional_info_new.append(validity_list)
additional_info_new.append(param)
self.fulllist_new = fulllist_new
self.fulllist_percent_new = fulllist_percent_new
self.fulllist_click_new = fulllist_click_new
self.additional_info_new = additional_info_new
self.validity_new = validity_new
return self.fulllist_new, self.fulllist_percent_new, self.fulllist_click_new, self.additional_info_new, self.validity_new
def saveSampleStr(self):
time = strftime("%d:%m:%Y %H-%M", gmtime())
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileNameSave, _ = QFileDialog.getSaveFileName(self,"Сохранить обработанную строку","./Processed","Excel files (*.xlsx)", options=options)
workbook = xlsxwriter.Workbook(fileNameSave + ' (' + time + ')' + ".xlsx")
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()
worksheet3 = workbook.add_worksheet()
worksheet4 = workbook.add_worksheet()
row = 0
for col, data in enumerate(self.fulllist_new):
worksheet1.write_column(row, col, data)
for col, data in enumerate(self.fulllist_percent_new):
worksheet2.write_column(row, col, data)
for col, data in enumerate(self.fulllist_click_new):
worksheet3.write_column(row, col, data)
for col, data in enumerate(self.additional_info_new):
worksheet4.write_column(row, col, data)
workbook.close()
def refreshSample(self):
sample_directory = []
sample_files = []
for (dirpath, dirnames, filenames) in walk('./Samples'):
filenames = [f for f in filenames if not f[0] == '.']
sample_files.extend(filenames)
break
the_dir = "Samples"
paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')]
sample_directory.append(sample_files)
sample_directory.append(paths)
self.sample_directory = sample_directory
self.sampleChoose_list.clear()
self.sampleChoose_list.addItems(sample_directory[0])
self.sampleChoose_list.setSortingEnabled(True);
self.sampleChoose_list.sortItems()
return self.sample_directory
def refreshSample_2(self):
sample_directory_2 = []
sample_files_2 = []
for (dirpath, dirnames, filenames) in walk('./Processed'):
filenames = [f for f in filenames if not f[0] == '.']
sample_files_2.extend(filenames)
break
the_dir = "Processed"
paths_2 = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')]
sample_directory_2.append(sample_files_2)
sample_directory_2.append(paths_2)
processed_info = []
for i in range(len(sample_directory_2[0])):
file_info = []
sample_file_2 = sample_directory_2[0][i]
sample_path_2 = sample_directory_2[1][i]
sample_info_2 = pd.read_excel(ospath(sample_path_2), header = None, sheetname = 3)
sample_info_2 = sample_info_2.iloc[0][0:3]
file_info.append(sample_file_2)
sample_info_2_list = numpy.array(sample_info_2).tolist()
file_info.extend(sample_info_2_list)
processed_info.append(file_info)
self.clickSample_list.setRowCount(len(processed_info))
self.clickSample_list.setColumnCount(4)
labels = ['Имя', 'Массовые отклики', 'Процентранг, %', 'Валидность']
self.clickSample_list.setHorizontalHeaderLabels(labels)
red = QtGui.QColor(255, 5, 5);
orange = QtGui.QColor(255, 157, 0);
blue = QtGui.QColor(0, 46, 255);
for row in range(len(processed_info)):
for column in range(len(processed_info[row])):
self.clickSample_list.setItem(row, column, QTableWidgetItem(str(processed_info[row][column])))
if column == 2:
if processed_info[row][column] > 85:
color = red;
if processed_info[row][column] > 65 and processed_info[row][column] < 85:
color = orange;
if processed_info[row][column] < 65:
color = blue;
self.clickSample_list.item(row, column).setBackground(color);
self.clickSample_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyMainWindow()
sys.exit(app.exec_())
my app is launched in a window and UI is loaded by from ui_main import Ui_MainWindow. My question is, how to make a desktop app? Do I need to do it in special Qt5 creator files? Or is possible to make it out of .ipynb-file from Anaconda? I am trying to make both MacOs and Windows versions, but I am pretty new to app-building and programming and do not know, how to begin.
You can use cx_Freeze to create a desktop app from a python program.
There's a guide to packaging a PyQt application:
cxfreeze-quickstart # generates a creation script
On OSX, you have the option of building a .dmg or a .app, by executing one of these at the prompt:
python setup.py bdist_dmg
python setup.py bdist_mac
On Windows:
python setup.py bdist_msi
There's a comparison of deployment tools here.

Categories