I have a code that reads the csv file and calculates the liquid output. it was working for previous csv files but now for an updated csv file it is giving output as 0.0. Can anyone explain any glitch in the code?
My code is below:
import csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
import datetime
#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="Measure The Urine", command=self.takedate)
button3 = Button(self, text="Exit", command=master.destroy)
button1.grid()
button2.grid()
button3.grid()
l1 = Label(self, text="Enter from date (2017/01/01)")
l1.grid()
self.userInputFromRaw = Entry(self)
self.userInputFromRaw.grid()
l2 = Label(self, text="Enter to date (2017/01/01)")
l2.grid()
self.userInputToRaw = Entry(self)
self.userInputToRaw.grid()
self.output = Text(self)
self.output.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
self.output.insert(END, "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()
my csv file looks like this:
2 2017/02/17 19:06:17.188
Related
New to Tkinter
I have a json file which contains some Firewall-rules, then convert it into two different csvs. As the firewall-rules have two different sets with ARules.csv and YRules.csv Don't want to merge it because of the requirement.
Then using splunk we pull the stats which will generate firewall-rules for that day. We then export it with the name - logReport.csv. Let's say there are 50 rows of data
check the results of logReport (data) is present in both the csvs[ARules(150 rows) and YRules(100 rows)]
ARules.loc[ARules['name'].isin(logReport['data'])] - [result - 30]
YRules.loc[YRules['name'].isin(logReport['data'])] - [result - 20]
What I am trying to achieve here is to create a process, where I call the api, and convert that JSON into multiple csv and display it in "tkinter" in two different frames one for ARules and other for YRules, then ask the user to import that logReport.csv using "filedialog or opencsv" and then get the matching/difference results and export it to csv.
my code
import pandas as pd
import json
f = open("/Users/Documents/Info/data.json")
data = json.load(f)
f.close()
ARules = pd.DataFrame(data['ARules'])
YRules = pd.DataFrame(data['YRules'])
csvfile = "/Users/Downloads/logReport.csv"
logReport = pd.read_csv(csvfile,error_bad_lines=False, engine="python")
ARulesV1 = ARules.loc[ARules['ARules'].isin(logReport['data'])]
YRulesV1 = XRules.loc[XRules['YRules'].isin(logReport['data'])]
I was able to do this much but not able to display the output on GUI.
import pandas as pd
import csv
import json,os
from tkinter import *
import tkinter as tk
from tkinter.filedialog import askopenfilename
def import_csv_data():
global v
csv_file_path = askopenfilename()
v.set(csv_file_path)
colnames=['rules', 'count']
logReport = pd.DataFrame(pd.read_csv(csv_file_path,error_bad_lines=False,names=colnames, header=None, engine="python"))
logReport.drop(logReport.index[0],inplace=True)
search(logReport)
def search(logReport):
f = open("/Users/Documents/Info/data.json")
data = json.load(f)
f.close()
ARules = pd.DataFrame(data['ARules'])
YRules = pd.DataFrame(data['YRules'])
print("Total Number of ARules:",ARules.shape[0])
print("Total Number of YRules:",YRules.shape[0])
print()
print("Stats Report from Splunk:",logReport.shape[0])
print("Number of Rules Triggered in ARules:",ARules.loc[ARules['name'].isin(logReport['data'])].shape[0])
print("Number of Rules Triggered in YRules:",YRules.loc[YRules['name'].isin(logReport['data'])].shape[0])
window = tk.Tk()
window.title("Search CSV")
frame = Frame(window, width=500, height=500)
frame.pack()
tk.Label(frame, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(frame, textvariable=v,width=30).grid(row=0, column=1)
tk.Button(frame, text='Browse',command=import_csv_data).grid(row=1, column=0)
lbl3 = tk.Label(frame, text = "Total Number of Rules: ").grid(row = 3, column = 1)
window.mainloop()
Want to display the print details on GUI
import pandas as pd
import csv
import json,os
from tkinter import *
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
def import_csv_data():
global v,csvData
csv_file_path = askopenfilename()
v.set(csv_file_path)
colnames=['rules', 'count']
csvData = pd.DataFrame(pd.read_csv(csv_file_path,error_bad_lines=False,names=colnames, header=None, engine="python"))
csvData.drop(csvData.index[0],inplace=True)
search()
def loadJson():
global data
name = askopenfilename(initialdir="../Path/For/JSON_file",
filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
title="Choose a file."
)
try:
f = open(name)
data = json.load(f)
f.close()
except Exception:
messagebox.showerror("Error Message", 'File Corrupted’)
def search():
global Adata, Ydata
Adata = pd.DataFrame(data['Arules'])
Ydata = pd.DataFrame(data['Yrules'])
adata.config(text=Adata.shape[0])
ydata.config(text=Ydata.shape[0])
tData.config(text=csvData.shape[0])
AResult.config(text=Adata.loc[Adata['name'].isin(csvData['rules'])].shape[0])
YResult.config(text=Ydata.loc[Ydata['name'].isin(csvData['rules'])].shape[0])
def write_to_csv():
notTriggered = Adata['name'].loc[~Adata['name'].isin(csvData['rules'])]
notTriggered2 = Ydata['name'].loc[~Ydata['name'].isin(csvData['rules'])]
bigResult = notTriggered.append(notTriggered2, ignore_index=True)
name = asksaveasfile(initialfile = 'Untitled.csv’,mode='w',
defaultextension=".csv",filetypes=[("All Files","*.*"),("Text Documents","*.txt")])
if name:
bigResult.to_csv(name)
name.close()
window = tk.Tk()
window.title("Search Match Alerts“)
frame = Frame(window, width=500, height=500)
frame.pack()
tk.Label(frame, text='File Path').grid(row=1, column=0)
v = tk.StringVar()
entry = tk.Entry(frame, textvariable=v,width=40).grid(row=1, column=1)
tk.Button(frame, text='Import Json',command=loadJson).grid(row=0, column=0)
tk.Button(frame, text='Browse',command=import_csv_data).grid(row=2, column=0)
tk.Button(frame, text='Export',command=write_to_csv).grid(row=2, column=3)
font1 = ("Arial", 14)
tk.Label(frame, text = "Total Number of ARules: ").grid(row = 3, column = 0)
adata = Label(frame, font=font1)
adata.grid(row=3, column=1, sticky=W)
tk.Label(frame, text = "Total Number of YRules: ").grid(row = 4, column = 0)
ydata = Label(frame, font=font1)
ydata.grid(row=4, column=1, sticky=W)
tk.Label(frame, text = "Stats Report from Splunk: ").grid(row = 5, column = 0)
tData = Label(frame, font=font1)
tData.grid(row=5, column=1, sticky=W)
tk.Label(frame, text = "No. of Match Result on ARules: ").grid(row = 6, column = 0)
AResult = Label(frame, font=font1)
AResult.grid(row=6, column=1, sticky=W)
tk.Label(frame, text = "No. of Match Result on YRules: ").grid(row = 7, column = 0)
YResult = Label(frame, font=font1)
YResult.grid(row=7, column=1, sticky=W)
window.mainloop()
I am currently making a GUI with Tkinter that plays music. The program is able to correctly play the songs, and I am trying to implement a pause button. This is the code I have, does anyone know why this might not be working? I know the button is linked properly since I have tried printing something out when the button is clicked, and that works. Also, there are no error messages, the audio is just not pausing.
import pygame
from tkinter import *
import os
import urllib.request
import urllib.parse
import re
import requests
from PIL import ImageTk, Image
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
pygame.mixer.init()
self.downloadNum = 1
self.pack(fill = BOTH, expand = 1)
self.songDict = {}
num = 1
while True:
if os.path.exists(str(num)+'.jpg'):
os.remove(str(num)+'.jpg')
num += 1
else:
break
self.create_widgets()
def create_widgets(self):
Label(self, text="Available Songs").grid(row=0, column=0)
for filename in os.listdir(r'C:\Users\alvin\Documents\School'):
if filename.endswith(".mp3"):
string = ""
for x in filename:
if x == "_":
string += " "
else:
if x == ".":
break
string += x
Label(self, text=string).grid()
Label(self, text = "Enter your song!").grid(row=0, column = 1)
self.entryBox = Entry(self)
self.entryBox.grid(row=1, column =1)
Button(self, text="Play!", command = self.playSong).grid(row=2, column =1)
Label(self).grid(row=3, column =1)
Label(self, text="Currently Playing:").grid(row=4, column=1)
self.playing = Label(self, text="")
self.playing.grid(row=5, column=1)
def playSong(self):
self.song = self.entryBox.get()
self.newsong = ""
for x in self.song:
if x == " ":
self.newsong += "_"
else:
self.newsong += x
self.newsong = self.newsong.title()
self.newsong = self.newsong + ".mp3"
pygame.mixer.music.load(self.newsong)
pygame.mixer.music.play(0)
self.playing.configure(text=self.song.title())
query_string = urllib.parse.urlencode({"search_query": self.song.title()})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
f = open(str(self.downloadNum) +'.jpg','wb')
f.write(requests.get('https://img.youtube.com/vi/' + search_results[0] + '/default.jpg').content)
f.close()
self.songDict[self.downloadNum] = self.newsong
load = Image.open(str(self.downloadNum) + ".jpg")
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=145, y=135)
self.downloadNum += 1
Label(self).grid(row=6, column =0)
Label(self).grid(row=7, column=0)
Label(self).grid(row=8, column=0)
Label(self).grid(row=9, column=0)
Label(self).grid(row=10, column=0)
pauseButton = Button(self, text="||", command = self.pause)
pauseButton.grid(row = 11, column = 1)
def pause(self):
pygame.mixer.pause()
root = Tk()
root.title("MP3 Player")
root.geometry("400x400")
app = Application(root)
root.mainloop()
try using:
pygame.mixer.music.pause()
instead of:
pygame.mixer.pause()
I'm having a peculiar problem when displaying a widget containing a tkinter.StringVar variable.
This happens whether or not I use frames to locate the variable.
In brief, I have three non-variable labels, one variable label, a progressbar and two buttons all gridded vertically (the button are side by side though (irrelevant but supplied for completeness).
When the variable is changed programmatically, concatenating a new character ('\n) and more text, the variable shows the extra lines, but duplicate progressbars and buttons are displayed:
(Separate images here).
Interesting note: This does not happen if the '\n' is not added.
import os
import sys
import time
import tkinter as tk
import tkinter.ttk as ttk
class rtGetPaths(tk.Frame):
"""
"""
def __init__(self, root):
tk.Frame.__init__(self, root)
self.root = root
# Get the system separator
self.path_sep = os.pathsep
# Find the root on the drive
self.root_id = os.path.abspath(os.sep)
self.data = [(os.path.join('C:', 'Program Files', 'App_1.exe')),
(os.path.join('C:', 'Program Files', 'App_2.exe')),
(os.path.join('C:', 'Program Files', 'App_3.exe')),
(os.path.join('C:', 'Program Files', 'App_4.exe'))
]
self.locns = []
self.root.title('Get Paths')
self.gpw_l1 = tk.Label(self.root, text='Searching for apps')
self.gpw_l2 = tk.Label(self.root, text='This may take some time')
self.gpw_l3 = tk.Label(self.root, text='Please be patient')
self.gpw_found_l_svar = tk.StringVar()
self.gpw_found_l_svar.set('')
self.gpw_found_l = tk.Label(self.root, textvariable=self.gpw_found_l_svar)
self.gpw_pb_ivar = tk.IntVar()
self.gpw_pb_ivar.set(0)
self.gpw_pb_length = 350
self.gpw_pb_max = 5
self.gpw_pb = ttk.Progressbar(self.root,
mode='determinate',
maximum=self.gpw_pb_max,
length=self.gpw_pb_length,
variable=self.gpw_pb_ivar)
self.gpw_exit_b = tk.Button(self.root,
text='Exit',
command=sys.exit)
self.gpw_continue_b = tk.Button(self.root,
text='Continue',
command=self.gpw_action_continue_b)
row = 0
self.gpw_l1.grid(row=row, columnspan=2)
row += 1
self.gpw_l2.grid(row=row, columnspan=2)
row += 1
self.gpw_l3.grid(row=row, columnspan=2)
row += 1
self.gpw_found_l.grid(row=row, columnspan=2)
row += 1
self.gpw_pb.grid(row=row, columnspan=2)
row += 1
self.gpw_exit_b.grid(row=row, column=0, sticky='ew')
self.gpw_continue_b.grid(row=row, column=1, sticky='ew')
self.gpw_found_l.grid_remove()
self.root.geometry('+100+200')
def gpw_action_continue_b(self):
"""
:return:
"""
for file in self.data:
lookfor = ''
if 'App_1.exe' in file:
lookfor = file
elif 'App_2.exe' in file:
lookfor = file
elif 'App_3.exe' in file:
lookfor = file
elif 'App_4.exe' in file:
lookfor = file
if lookfor != '':
self.locns.append(lookfor)
label = self.gpw_found_l_svar.get()
if 0 < self.gpw_pb_ivar.get() < 5:
label = label + '\n'
label = label + os.path.join(lookfor)
self.gpw_found_l_svar.set(label)
self.gpw_pb_ivar.set(self.gpw_pb_ivar.get() + 1)
if not self.gpw_found_l.winfo_viewable():
self.gpw_found_l.grid()
self.root.update_idletasks()
time.sleep(1)
self.gpw_continue_b['state'] = 'disabled'
self.gpw_pb_ivar.set(self.gpw_pb_max)
self.root.update_idletasks()
return
#==============================================================================
# MAIN (MAIN)
#==============================================================================
def main():
""" Run the app
"""
# # Create the screen instance and name it
root = tk.Tk()
app = rtGetPaths(root)
root.mainloop()
root.quit()
#==============================================================================
# MAIN (STARTUP)
#==============================================================================
if __name__ == '__main__':
# Run the function name main()
main()
Why is it doing this, and how do I stop it?
I'm not sure why this problem is occurring, but you can fix it by updating the progress bar each time you change the lable
The code:
def gpw_action_continue_b(self):
for file in self.data:
...
self.gpw_pb.update() # this fixes the problem
self.root.update_idletasks()
time.sleep(1)
Proof it works:
I am new to python and trying to build a GUI that takes from date and to date from user and reads the data accordingly from a csv file and display the urine output (calculated in the csvimport fucntion). I also want to plot the graph for a specific time and urine output in that time.
Can anyone help me? My code so far is below and it isn't displaying any GUI. Please can anyone correct the basic errors and help me in running this?
import csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
import datetime
#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)
self.in_file = None
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.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(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 = raw_input('\nEnter FROM Date (e.g. 2013-11-29) :')
from_date = datetime.date(*map(int, from_raw.split('/')))
print ('From date: = ' + str(from_date))
to_raw = raw_input('\nEnter TO Date (e.g. 2013-11-30) :')
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()
You are calling takedate method as soon as you are initializing your class. Removing parentheses(which means, call the method) would solve your issue.
button2 = Button(self, text="Count the file", command=self.takedate())
^^ remove these
Your GUI doesn't show up because takedate method makes your program to wait for user input because of raw_input(..) calls.
You should consider using Entry instead of raw_input() for getting user input.
EDIT: You can put two Entry in your __init__ then use Entry's get method in takedate. Roughly something like below.
def __init__(self, master):
...
...
self.userInputFromRaw = Entry(self)
self.userInputFromRaw.grid()
self.userInputToRaw = Entry(self)
self.userInputToRaw.grid()
def takedate(self):
...
from_raw = self.userInputFromRaw.get()
...
to_raw = self.userInputToRaw.get()
Also, you should add self parameter when defining your method since it is part of that class.
def CsvImport(self, csv_file):
If you not want to pass parameters into self.takedate() remove ()as below:
button2 = Button(self, text="Count the file", command=self.takedate)
or change to
button2 = Button(self, text="Count the file", command=lambda e=Null: self.takedate())
In this case you can pass e parameter to self.takedate(). Pass it to this maner:
command=lambda e=Null: self.takedate(e)
def takedate(self, parameter): pass
I am trying to develop a class population counter. The problem is that when I run it 2 program come up. I wanted my program to be all in one. The counter keeps coming in a separate program and i can't transfer it into my actual program. How do I do this?
Here is my attached files, I am using Python
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = tk.Tk()
label = tk.Label(root)
label.pack()
counter_label(label)
button = tk.Button(root, text='Population Count', command=count).pack()
root.mainloop()
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
I think two windows are coming up is because the program runs Tk() twice - one root = tk.Tk() and another in window = Tk(). If you pass your root Tkinter instance to the class ClassPopulation, then it should show one single window.
[EDIT]
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self, root_window):
window = self.root_window
window.title("Class population")
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = Tk()
label = tk.Label(root)
label.pack()
ClassPopulation( root )
counter_label(label)
root.mainloop()