The application should search one of the column in an excel and and display corresponding column as a result but i am not able to get the values. I think i am not able to map the dictionary to the display tab using tkinter. Please help.
Below file is in outlook
Search (Input) Result (Output)
1 a
2 b
3 c
4 d
from tkinter import *
import tkinter.messagebox
import pandas as pd
root=Tk()
root.geometry('450x550')
root.title("Welcome")
root.configure(background="silver")
#Entry widget object
textin=StringVar()
**exlist = pd.read_excel('foo6.xls', index_col=0).to_dict('index')**
def clk():
entered = ent.get()
output.delete(0.0,END)
try:
textin = exlist[entered]
except:
textin = 'SORRY NO INFO \n AVAILABLE!!!!!!!!\n'
output.insert(0.0,textin)
def ex():
tkinter.messagebox.showinfo("Program",'Exit')
exit()
def exitt():
tkinter.messagebox.showinfo("Program",'Exit')
exit()
def me():
text='\n XYZ \n Piyushrkc \n Nice'
saveFile=open('text.txt','w')
saveFile.write(text)
print('This are the entries::',text)
def hel():
help(tkinter)
def cont():
tkinter.messagebox.showinfo("S/W Contributors",'\n Piyush ___Version 1.0___')
def clr():
textin.set(" ")
menu = Menu(root)
root.config(menu=menu)
subm = Menu(menu)
menu.add_cascade(label="File",menu=subm)
subm.add_command(label="Memo",command=me)
subm.add_command(label="Save")
subm.add_command(label="Save As")
subm.add_command(label="Print")
subm.add_command(label="Exit",command=ex)
subm1 = Menu(menu)
menu.add_cascade(label="Tools",menu=subm1)
subm1.add_command(label="Tkinter Help",command=hel)
subm2 = Menu(menu)
menu.add_cascade(label="About",menu=subm2)
subm2.add_command(label="Contributors",command=cont)
lab=Label(root,text='Name :',font=('none 20 bold'))
lab.grid(row=0,column=1,sticky=W)
ent=Entry(root,width=20,font=('none 18 bold'),textvar=textin,bg='white')
ent.grid(row=0,column=2,sticky=W)
but=Button(root,padx=2,pady=2,text='Submit',command=clk,bg='powder blue',font=('none 18 bold'))
but.place(x=100,y=90)
but4=Button(root,padx=2,pady=2,text='Clear',font=('none 18 bold'),bg='powder blue',command=clr)
but4.place(x=220,y=90)
output=Text(root,width=20,height=8,font=('Time 20 bold'),fg="black")
output.place(x=100,y=200)
labb=Label(root,text='Results',font=('non 18 bold'))
labb.place(x=0,y=180)
but1=Button(root,padx=2,pady=2,text='Exit',command=exitt,bg='powder blue',font=('none 18 bold'))
but1.place(x=200,y=470)
root.mainloop()
Related
i dont know why i cannot put all of my code
i created a function w3 and i add some checkbuttons the problem is that if the user clicks "< Υποβολή >" the function listokouti only recognizes the messagebox and its like i never put elif,can anyone help?
i1=IntVar()
i2=IntVar()
i3=IntVar()
i4=IntVar()
i5=IntVar()
#i6=IntVar()
#i7=IntVar()
# checkbuttons
check1 = tk.Checkbutton(rain,text="Τίτλος",font=('',13),variable=i1,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check2 = tk.Checkbutton(rain,text="Tίτλος(Μετάφραση)",font=('',13),variable=i2,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check3 = tk.Checkbutton(rain,text="Συγγραφέας",font=('',13),variable=i3,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check4 = tk.Checkbutton(rain,text="Λέξεις κλειδιά",font=('',13),variable=i4,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check5 = tk.Checkbutton(rain,text="Λέξεις κλειδιά(Μετάφραση)",font=('',13),variable=i5,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
def listokouti():
if i1.get()==0 and i2.get()==0 and i3.get()==0 and i4.get()==0 and i5.get()==0 :
vsause=messagebox.showwarning("team.33","Παρακαλώ επιλέξτε φίλτρα")
elif i1.get()==1 or i2.get()==1 or i3.get()==1 or i4.get()==1 or i5.get()==1 :
money=tk.Tk()
money.title("team.33")
money.iconbitmap('C:\Program Files (x86)\icon.ico')
# money.config(bg="#000000")
frame=tk.Frame(money)
scrollarw1=ttk.Scrollbar(frame,orient=VERTICAL)
my_listbox= tk.Listbox(frame,yscrollcommand=scrollarw1.set,width=50)
scrollarw1.config(command=my_listbox.yview)
scrollarw1.pack(side=RIGHT,fill= Y)
scrollarw2=ttk.Scrollbar(frame,orient=HORIZONTAL)
scrollarw2.config(command=my_listbox.xview)
scrollarw2.pack(side=BOTTOM,fill= X)
frame.pack()
my_listbox.pack(pady=20)
# to item einai akyro to evala mono gia na leitoyrgei to scrollbar
for item in range(1,101):
my_listbox.insert(END,item)
butt =tk.Button(money,text="< Υποβολή >",font=("",10,'bold'),command=ergasia).pack()
money.mainloop()
b1 = tk.Button(rain,text="< Υποβολή >",font=("",10,"bold"),command= listokouti).pack(expand=1)
rain.mainloop()
w3()
*I wanted to bind platform_id drop combobox to teh combobox_b so taht if cpu is selected in platform_id_drop, then cpu frequencies must be listed otherwise gpu frequencies must be listed. I am using while loop to create a number of rows based on input we are giving and used dictionary to store respective columns. I am able to get only fo rone set of row i.e frequencies are display oly for one row but not for other rows. Having Problem with bind function. Please help me with this.
'''
import pandas as pd
from tkinter import filedialog
from tkinter import ttk
from tkinter.filedialog import asksaveasfile
import collections
app=Tk()
app.title("trace")
app.geometry("1000x500")
global z
required=2
z=required
global global_id
global_id=0
global text_file_3
global text_file_4
a_dict = collections.defaultdict(list)
a_dict['global_id']={}
a_dict['unique_dag_id']={}
a_dict['platform_id']={}
a_dict['deadline']={}
a_dict['wcet_cpu']={}
a_dict['wcet_gpu']={}
a_dict['input_arrival_time']={}
a_dict['hyper_period_entry']={}
a_dict['input_task_period']={}
a_dict['frequency']={}
unique_dag_id = StringVar()
wcet_cpu = StringVar()
wcet_gpu = StringVar()
deadline = StringVar()
input_arrival_time = StringVar()
hyper_period_entry = StringVar()
input_task_period=StringVar()
frequency=StringVar()
last_county=StringVar()
v=[]
dict1={'gpu':['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000'],'cpu':['200000000', '300000000', '400000000', '500000000', '600000000', '700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']}
def save_trace1():
global global_id
global_id_info=global_id_entry
if(platform_id_drop.get()=='cpu'):
platform_id_info=0
else:
platform_id_info=1
unique_dag_id_info=unique_dag_id_entry
wcet_cpu_info=wcet_cpu_entry.get()
wcet_gpu_info=wcet_gpu_entry.get()
deadline_info=deadline_entry.get()
input_arrival_time_info=input_arrival_time_entry.get()
hyper_period_entry_info=hyper_period_entry_entry.get()
input_task_period_info=input_task_period_entry.get()
combobox_b_info=combobox_b.get()
for i in range(required):
print(a_dict['platform_id'][i].get())
global_id_label=Label(text="global_id ")
platform_id_label=Label(text='platform_id')
unique_dag_id_label=Label(text='unique_dag-id')
wcet_cpu_label=Label(text='wcet_cpu')
wcet_gpu_label=Label(text='wcet_gpu')
deadline_label=Label(text='deadline')
input_arrival_time_label=Label(text='input-arrival time')
hyper_period_entry_label=Label(text='hyper_period_entry')
input_task_period_label=Label(text='input_task_period')
freq_label=Label(text='Frequency')
platform_id_options=[
'cpu','gpu',
]
global_id_label.place(x=50,y=50)
platform_id_label.place(x=150,y=50)
unique_dag_id_label.place(x=330,y=50)
wcet_cpu_label.place(x=450,y=50)
wcet_gpu_label.place(x=600,y=50)
deadline_label.place(x=750,y=50)
input_arrival_time_label.place(x=900,y=50)
hyper_period_entry_label.place(x=1050,y=50)
input_task_period_label.place(x=1200,y=50)
freq_label.place(x=1350,y=50)
trace_entries=[]
dag_entries=[]
while(z>0):
#platform_id_drop.pack(pady=20)
def selo(eventobj):
v=[]
if(platform_id_drop.get()=='cpu'):
print("a")
v=['200000000', '300000000', '400000000', '500000000', '600000000',
'700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']
elif(platform_id_drop.get()=='gpu'):
print("m")
v=['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000']
global_id_entry=Label(text=str(global_id))
global_id_entry.place(x=50,y=50+60*(global_id+1))
a_dict['global_id'][global_id]=global_id
unique_dag_id_entry=Label(text=str(global_id))
unique_dag_id_entry.place(x=330,y=50+60*(global_id+1))
a_dict['unique_dag_id'][global_id]=unique_dag_id_entry
wcet_cpu_entry=Entry(app)
wcet_cpu_entry.place(x=450,y=50+60*(global_id+1))
a_dict['wcet_cpu'][global_id]=wcet_cpu_entry
wcet_gpu_entry=Entry(app)
wcet_gpu_entry.place(x=600,y=50+60*(global_id+1))
a_dict['wcet_gpu'][global_id]=wcet_gpu_entry
deadline_entry=Entry(app)
deadline_entry.place(x=750,y=50+60*(global_id+1))
a_dict['deadline'][global_id]=(deadline_entry)
input_arrival_time_entry=Entry(app)
input_arrival_time_entry.place(x=900,y=50+60*(global_id+1))
a_dict['input_arrival_time'][global_id]=(input_arrival_time_entry)
hyper_period_entry_entry=Entry(app)
hyper_period_entry_entry.place(x=1050,y=50+60*(global_id+1))
a_dict['hyper_period_entry'][global_id]=(hyper_period_entry_entry)
input_task_period_entry=Entry(app)
input_task_period_entry.place(x=1200,y=50+60*(global_id+1))
a_dict['input_task_period'][global_id]=( input_task_period_entry)
platform_id_drop=ttk.Combobox(app,values=platform_id_options)
platform_id_drop.bind("<<ComboboxSelected>>",selo)
platform_id_drop.place(x=150,y=50+60*(global_id+1))
a_dict['platform_id'][global_id]=platform_id_drop
combobox_b = ttk.Combobox(app,values=v)
combobox_b.place(x=1350,y=50+60*(global_id+1))
a_dict['frequency'][global_id]=( combobox_b )
v.clear()
global_id=global_id+1
z=z-1
button=Button(app,text="save_info",command=save_trace1)
button.place(x=0,y=0)
app.mainloop()
'''
I creating GUI interacting with treeview and I want to get all the value inside the list and show it in treeview window. I have a add button and once I click it, it will work fine. But on the second time, it shows an error Item 1 already exists. It also does not added to the list.
This is my code:
from tkinter import *
from tkinter import ttk
root = Tk()
def add1():
global count
for i in tree_table.get_children():
tree_table.delete(i)
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
data_list.append((get_name, get_ref, get_age, get_email))
for item in data_list:
tree_table.insert(parent='', index='end', iid=count, text=f'{count + 1}', values=(item))
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
count += 1
print(data_list)
tree_table = ttk.Treeview(root)
global count
count = 0
data_list = []
tree_table['columns'] = ("Name", "Reference No.", "Age", "Email Address")
tree_table.column("#0", width=30)
tree_table.column("Name", width=120, anchor=W)
tree_table.column("Reference No.", width=120, anchor=W)
tree_table.column("Age", width=120, anchor=W)
tree_table.column("Email Address", width=120, anchor=W)
headings = ["#0", "Name", "Reference No.", "Age", "Email Address"]
txt_headings = ["No.", "Name", "Reference No.", "Age", "Email Address"]
for i in range(len(headings)):
tree_table.heading(headings[i], text=txt_headings[i], anchor=W)
txt_name = Entry(root, width=20)
txt_name.pack()
txt_ref = Entry(root, width=20)
txt_ref.pack()
txt_age = Entry(root, width=20)
txt_age.pack()
txt_email = Entry(root, width=20)
txt_email.pack()
btn_enter = Button(root, text="Add", width=20, command=add1)
btn_enter.pack()
tree_table.pack()
root.mainloop()
Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\Python385\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Code/Cpet5/new.py", line 32, in add1
tree_table.insert(parent='', index='end', iid=count, text=f'{count + 1}', values=(item))
File "C:\Python\Python385\lib\tkinter\ttk.py", line 1366, in insert
res = self.tk.call(self._w, "insert", parent, index,
_tkinter.TclError: Item 1 already exists
How do I refresh the treeview to reflect the changes made in the list?
Quick fix:
Get rid of the iid argument:
tree_table.insert(parent='', index='end', text=f'{count + 1}', values=(item))
But that will create an issue of the No. column getting same value always.
Actual fix:
So the actual problem is your list contains alot of values, you should get rid of those values once you insert it, so the code should be something like:
def add1():
global count
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
data_list.clear() #clear the list
data_list.append((get_name, get_ref, get_age, get_email)) #append to the empty list
for item in data_list:
tree_table.insert(parent='', index='end',iid=count, text=f'{count + 1}', values=(item))
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
count += 1
print(data_list)
This way your clearing whats inside of the list each time and appending new values to list.
With your older code you can see that first time the the list is [('1', '1', '1', '1')] and when the next set of values is appended it becomes [('1', '1', '1', '1'), ('2', '2', '2', '2')] so there is not enough space accommodate all this value in? Anyway this fixes it. Or you could also make a tuple of those inputs and then pass that tuple as the values for treeview without looping, like acw1668 did.
You don't need to clear the treeview before adding new row to it:
def add1():
global count
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
row = (get_name, get_ref, get_age, get_email)
data_list.append(row)
count += 1
tree_table.insert(parent='', index='end', iid=count, text=f'{count}', values=row)
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
print(data_list)
This question already has an answer here:
Override global variable inside function not working with Spyder 4
(1 answer)
Closed 2 years ago.
So I am trying to run the program below, in Spyder, and am constantly faced with the following recurring error:
>Exception in Tkinter callback
>>Traceback (most recent call last):
>>>File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
>>>>return self.func(*args)
>>>>>File "C:/Users/WYoung3/Training Team Flight Program v.5.py", line 128, in TAFLIGHT
>>>>>>outputTAF (str(oppath))
>>>>>>>File "C:/Users/WYoung3/Training Team Flight Program v.5.py", line 98, in outputTAF
>>>>>>>>OP0_df.to_excel(writer, sheet_name='Origin-Dest. Airfare (Data)')
NameError: name 'OP0_df' is not defined
If I run the defined functions individually, the results work exactly as I expect but running the whole program results in that error every time. What might I be doing wrong?
import pandas as pd
import numpy as np
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
"""
Input
"""
# inputTAF(r'//data4/users2/wyoung3/My Documents/Salmann Project/test/1.xlsx')
def inputTAF (Fdata):
#for each file
# open tab 6
# Pull all data from row 4 onward for column C (Airfare)
# pull all data from row 4 onward from clumn B (Country)
stop_df = pd.read_excel(Fdata, sheet_name="6. Actual Expenses",skiprows=[0,1],usecols=[0])
stop = stop_df.loc[stop_df['Name'] == 'Total'].index[0]
airfare_df = pd.read_excel(Fdata, sheet_name="6. Actual Expenses",skiprows=[0,1],usecols=[1,2])
airfare_df.head()
airfare_df = airfare_df.iloc[:stop]
airfare_df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)
print(airfare_df)
print('airfare_done')
# open tab 4
# Pull the following entries:
# Estimated Expenses: L26, L29, L31, L33-L36, L38
# Actual Expenses: N26, N29, N31, N33-N36, N38
# Convert list of tuples into dataframe
workbook = load_workbook(Fdata, data_only=True)
workbook.sheetnames
sheet=workbook.worksheets[4]
l4=sheet["L23:N39"]
vl4 = [[l4[3][0].value,l4[3][2].value], [l4[5][0].value,l4[5][2].value], [l4[8][0].value,l4[8][2].value], [l4[6][0].value,l4[6][2].value],[l4[13][0].value,l4[13][2].value], [l4[4][0].value,l4[4][2].value],[l4[15][0].value,l4[15][2].value]]
df_vl4 = pd.DataFrame(vl4, columns = ['Estimated', 'Actual'])
df_vl4.head()
df_vl5=df_vl4.T
df_vl5.rename(columns={0 :'Airfare', 1 :'Hotel (086)', 2 :'Meals (084)', 3 :'Subsistence (087)', 4 :'Conference Materials', 5 :'Travel Allowance (085)', 6 :'Other Incidentals (039)'
}, inplace=True)
df_vl5.reset_index(drop=True, inplace=True)
print(df_vl5)
# open table 0
# Pull the following cells: B3-B8, B10, B13-B15,B20, B28
basic_df = pd.read_excel(Fdata, sheet_name="0. Event Data",skiprows=[0],usecols=[1])
basic_df.head()
basic_df=basic_df.filter(items = [0,1,2,3,4,5,7,10,11,12,17,25], axis =0)
# append output dataframes
airfare_df.insert(0,'Destination',basic_df.iat[4,0])
airfare_df.insert(0,'Mission ID', basic_df.iat[7,0])
airfare_df.insert(0,'DM',basic_df.iat[11,0])
global OP0_df
OP0_df = pd.DataFrame({'DM':[],'Mission ID':[], 'Destination':[], 'Country':[], 'Airfare':[]})
global OP1_df
OP1_df = pd.DataFrame({'Mission ID' :[], 'Country Name' :[], 'Start Date' :[], 'End Date' :[], 'DM Folder #' :[], 'Airfare' :[], 'Hotel (086)' :[], 'Meals (084)' :[], 'Subsistence (087)' :[], 'Conference Materials' :[], 'Travel Allowance (085)' :[], 'Other Incidentals (039)':[]})
global OP2_df
OP2_df = pd.DataFrame({'Mission ID' :[], 'Country Name' :[], 'Start Date' :[], 'End Date' :[], 'DM Folder #' :[], 'Airfare' :[], 'Hotel (086)' :[], 'Meals (084)' :[], 'Subsistence (087)' :[], 'Conference Materials' :[], 'Travel Allowance (085)' :[], 'Other Incidentals (039)':[]})
df_vl5.insert(0,'DM', basic_df.iat[11,0])
df_vl5.insert(0,'End Date',basic_df.iat[3,0])
df_vl5.insert(0,'Start Date',basic_df.iat[2,0])
df_vl5.insert(0,'Country Name',basic_df.iat[4,0])
df_vl5.insert(0,'Mission ID', basic_df.iat[7,0])
a_df = df_vl5.iloc[1]
est_df = df_vl5.iloc[0]
OP1_df = OP1_df.append(a_df, ignore_index=True)
OP2_df = OP2_df.append(est_df, ignore_index=True)
"""
Output
"""
# outputTAF(r'//data4/users2/wyoung3/My Documents/Salmann Project/Output/Complete Database (V. Wesley).xlsx')
def outputTAF (Foutput):
from time import localtime, strftime
T = strftime('--%m-%d-%Y',localtime())
with pd.ExcelWriter(Foutput+'\output'+T+'.xlsx', datetime_format='mmm d yyyy') as writer:
OP0_df.to_excel(writer, sheet_name='Origin-Dest. Airfare (Data)')
OP1_df.to_excel(writer, sheet_name='Quantitative (Merged Fund)')
OP2_df.to_excel(writer, sheet_name='Estimates File')
number_of_runs = str(len(IP))+" files have been processed"
runlabel=Label(root, text=number_of_runs)
runlabel.pack()
"""
Run
"""
#Instruct program to iterate over each file in a directory
import pathlib
# ipfilepath = pathlib.Path(r'\\data4\users2\wyoung3\My Documents\Salmann Project\test') #directory where files will be kept
# oppath = pathlib.Path(r'\\data4\users2\wyoung3\My Documents\Salmann Project\test\source.xlsx'), oppath.parents[0] #path to output file
def TAFLIGHT():
global IP
IP = [x for x in ipfilepath.glob('*') if not x.name == oppath.name]
i = 1
if i is not len(IP):
for filepath in IP:
inputTAF (str(filepath))
i = i + 1
else:
outputTAF (str(oppath))
pass
'''
GUI
'''
from tkinter import *
from tkinter import filedialog
import pathlib
root = Tk()
root.title('Training Team Flight Program')
root.geometry('320x200')
frame =LabelFrame(root,bg='Blue',height=100, width=30, padx=5,pady=5)
frame.pack(padx=10,pady=40)
frame2 = LabelFrame(frame, padx=5,pady=7.4)
frame2.grid(row=0,column=0)
frame3 = LabelFrame(frame)
frame3.grid(row=0,column=1)
def click1():
root.directory = filedialog.askdirectory()
outputbutton['state']='normal'
print(root.directory)
global ipfilepath
ipfilepath = pathlib.Path(root.directory)
print(ipfilepath)
def click2():
root.directory = filedialog.askdirectory()
Runbutton['state']='normal'
print(root.directory)
global oppath
oppath = pathlib.Path(root.directory)
print(oppath)
print('ipfilepath: ', ipfilepath)
# Creating a label widget
inputlabel = Label(frame2, bg='red', text='Costing Data Directory' )
inputbutton = Button(frame3, text='click', command = click1)
outputlabel = Label(frame2, bg='yellow', text='Output File' )
outputbutton = Button(frame3, text='click', command = click2, state = 'disabled')
Runlabel = Label(frame2, bg='Green', text='Run Program' )
Runbutton = Button(frame3, text='click', command = TAFLIGHT, state = 'disabled')
# Shoving it onto the screen
inputlabel.grid(row=0, column=0)
inputbutton.grid(row=0, column=1)
outputlabel.grid(row=1, column=0)
outputbutton.grid(row=1, column=1)
Runlabel.grid(row=2, column=0)
Runbutton.grid(row=2, column=1)
root.mainloop()
Based on the code you've shown, you define OP0_df in inputTAF, but your code may not run inputTAF before calling outputTAF so OP0_df never gets defined.
I am getting data from a CSV file in python for a specific date. Now, I want to get it for a specific time for example from 13:30 to 14:30 for a specific date.
My CSV file look like this:
15 2017/02/07 17:30:45.983
15 2017/02/07 17:30:51.109
16 2017/02/07 17:30:56.008
16 2017/02/07 17:31:01.029
and my current code is like this:
import csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
import datetime
import matplotlib.pyplot as plt
#csv_file = csv.reader(open("C:\Users\Lala Rushan\Downloads\ARIF Drop Monitoring Final\ARIF Drop Monitoring Final\DataLog.csv"))
from Tools.scripts.treesync import raw_input
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
button1 = Button(self, text="Browse for a file", command=self.askfilename)
button2 = Button(self, text="Count the file", command=self.takedate)
button3 = Button(self, text="Exit", command=master.destroy)
button1.grid()
button2.grid()
button3.grid()
self.userInputFromRaw = Entry(self)
self.userInputFromRaw.grid()
self.userInputToRaw = Entry(self)
self.userInputToRaw.grid()
self.grid()
def askfilename(self):
in_file = askopenfilename()
if not in_file.endswith(('.CSV')):
showwarning('Are you trying to annoy me?', 'How about giving me a CSV file, genius?')
else:
self.in_file=in_file
def CsvImport(self,csv_file):
dist = 0
for row in csv_file:
_dist = row[0]
try:
_dist = float(_dist)
except ValueError:
_dist = 0
dist += _dist
print ("Urine Volume is: %.2f" % (_dist*0.05))
def takedate(self):
from_raw = self.userInputFromRaw.get()
from_date = datetime.date(*map(int, from_raw.split('/')))
print ('From date: = ' + str(from_date))
to_raw = self.userInputToRaw.get()
to_date = datetime.date(*map(int, to_raw.split('/')))
in_file = ("H:\DataLog.csv")
in_file= csv.reader(open(in_file,"r"))
for line in in_file:
_dist = line[0]
try:
file_date = datetime.date(*map(int, line[1].split(' ')[1].split('/')))
if from_date <= file_date <= to_date:
self.CsvImport(in_file)
except IndexError:
pass
root = Tk()
root.title("Urine Measurement")
root.geometry("500x500")
app = App(root)
root.mainloop()
How can I get the data for a specific time and for a specific date?
Use pandas and its DataFrame container, as this is the ideal format for handling data and selecting it. See the example below:
import pandas as pd
df = pd.read_csv('eg.txt', header=None) # Read in the Data.
df.index = [pd.datetime.strptime(i, '%Y/%m/%d%H:%M:%S.%f') for i in (df[1] + df[2])] # Format the time into the index
here
>>> df
0 1 2 3
2017-02-07 17:30:45.983 15 2017/02/07 17:30:45.983 3.3
2017-02-07 17:30:51.109 15 2017/02/07 17:30:51.109 4.4
2017-02-07 17:30:56.008 16 2017/02/07 17:30:56.008 5.2
2017-02-07 17:31:01.029 16 2017/02/07 17:31:01.029 NaN
and you can select a time range you want using:
>>> df[pd.datetime(2017, 2, 7, 17, 30, 50):pd.datetime(2017, 2, 7, 17, 30, 58)] # Slice the wanted time
0 1 2 3
2017-02-07 17:30:51.109 15 2017/02/07 17:30:51.109 4.4
2017-02-07 17:30:56.008 16 2017/02/07 17:30:56.008 5.2
where the csv that generated the data is eg.txt which looks like.
15,2017/02/07,17:30:45.983,3.3
15,2017/02/07,17:30:51.109,4.4
16,2017/02/07,17:30:56.008,5.2
16,2017/02/07,17:31:01.029,NaN
You can then delete, make, move columns and data as you wish.