Listbox in Json file - python

I have a json file that i save my listbox data in. After i choose items (highlight) from the listbox and save my file then load it, the listbox items are stored in my file and they are printed but they are not highlighted. How can I highlight them so i can deselect and select again if i want to change my item selection?
THE CODE:
import tkinter as tk
import json
from tkinter.filedialog import askdirectory
root = tk.Tk()
root.title('Intialization')
value = []
def callback(listbox):
global value
value = [listbox.get(ratio) for ratio in listbox.curselection()]
def writeToJSONFile(path, fileName, data):
filePathNameWExt = path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
def check():
global value
data = {}
path = askdirectory()
data['items'] = value
writeToJSONFile(path, 'json', data)
def w():
window = tk.Toplevel(root)
window.title('Main')
global value
listbox = tk.Listbox(window, activestyle='dotbox', selectmode=tk.MULTIPLE, exportselection=False)
values = [100, 155, 200, 255, 300, 355, 400]
for item in values:
listbox.insert(tk.END, item)
scrollbar = tk.Scrollbar(window)
scrollbar.grid(column=0, row=2, sticky='nse', pady=20)
listbox.bind('<<ListboxSelect>>', func=lambda z: callback(listbox))
listbox.config(width=13, height=4, yscrollcommand=scrollbar.set)
listbox.grid(column=0, row=2, pady=20, sticky='ne')
save_config = tk.Button(window, text="Save Configuration", bg='green', command=lambda: check())
save_config.grid(column=0, row=3)
try:
f = open('json.json', "r")
j = json.loads(f.read())
for key, value in j.items():
print(key, ":", value)
value = j['items']
print(j)
except FileNotFoundError:
print("No Json File")
window.grab_set()
load_btn = tk.Button(root, text="Load", command=w)
load_btn.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
root.mainloop()

After you read this json file,you could get the index of values and make those items selected.
Try:
import tkinter as tk
import json
from tkinter.filedialog import askdirectory
root = tk.Tk()
root.title('Intialization')
value = []
def callback(listbox):
global value
value = [listbox.get(ratio) for ratio in listbox.curselection()]
def writeToJSONFile(path, fileName, data):
filePathNameWExt = path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
def check():
global value
data = {}
path = askdirectory()
data['items'] = value
writeToJSONFile(path, 'json', data)
def w():
window = tk.Toplevel(root)
window.title('Main')
global value
listbox = tk.Listbox(window, activestyle='dotbox', selectmode=tk.MULTIPLE, exportselection=False)
values = [100, 155, 200, 255, 300, 355, 400]
for item in values:
listbox.insert(tk.END, item)
scrollbar = tk.Scrollbar(window)
scrollbar.grid(column=0, row=2, sticky='nse', pady=20)
listbox.bind('<<ListboxSelect>>', func=lambda z: callback(listbox))
listbox.config(width=13, height=4, yscrollcommand=scrollbar.set)
listbox.grid(column=0, row=2, pady=20, sticky='ne')
save_config = tk.Button(window, text="Save Configuration", bg='green', command=lambda: check())
save_config.grid(column=0, row=3)
try:
f = open('json.json', "r")
j = json.loads(f.read())
for key, value in j.items():
print(key, ":", value)
value = j['items']
index_list = [values.index(i) for i in value] # get the index
for index in index_list:
listbox.selection_set(index) # make it selected
f.close()
except FileNotFoundError:
print("No Json File")
window.grab_set()
load_btn = tk.Button(root, text="Load", command=w)
load_btn.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
root.mainloop()

Related

Getting index by name

I am currently on my first somewhat To Do App and i have trouble with deleting things. I dont actually understand how to properly get the value to search it by index.
import json
import tkinter as tk
class JsonArrayStore:
def __init__(self, filename):
self.filename = filename
self.__load()
def __load(self):
try:
f = open(self.filename, 'r')
self.info = json.load(f)
f.close()
except FileNotFoundError:
self.info = []
def __save(self):
with open(self.filename, 'w') as f:
json.dump(self.info, f)
def append(self, data, force_save=True):
self.info.append(data)
if force_save:
self.__save()
def remove(self, index, force_save=True):
del self.info[index]
if force_save:
self.__save()
class ToDoGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Don't Forget!")
self.geometry('600x400+200+100')
self.configure(bg='#eae5e1')
self.logo_bg = tk.Frame(master=self, height=20, width=3000)
self.logo_bg.pack()
self.logo_text = tk.Label(master=self.logo_bg, bg = '#599D9C',
width=3000,
text="Kelpie's To Do App!",
font=('Impact', 45), fg='white')
self.logo_text.pack()
self.add_button_frame = tk.Frame(master=self, bg='#eae5e1')
self.add_button_frame.pack(fill='x')
self.label_border = tk.Label(master=self.add_button_frame, bg='#eae5e1',
bd=12, width='500')
self.label_border.pack()
self.add_btn = tk.Button(master=self.label_border, text='Add Task!', command=self.on_button)
self.add_btn.pack(side='right', padx=10)
# Later: Add a placeholder func
self.add_text = tk.Entry(master=self.label_border)
self.add_text.insert(0, '')
self.add_text.pack(side='left', padx=10)
# Frames for tasks
self.task_frame = tk.Frame(master=self)
self.task_frame.pack()
# load from json file
a = JsonArrayStore('test1.json')
for i in a.info:
add_task_label = tk.Label(master=self, bg='red', text=f'{i}')
add_task_label.pack()
delete_btn = tk.Button(self, bg='green', text='Delete', command=self.del_btn)
delete_btn.pack()
def on_button(self):
a = JsonArrayStore('test1.json')
a.append(self.add_text.get())
task = tk.Label(master=self, bg='red', text=f'{self.add_text.get()}')
task.pack()
delete_btn = tk.Button(self, bg='green', text='Delete', command=self.del_btn)
delete_btn.pack()
def del_btn(self):
a = JsonArrayStore('test1.json')
x = a.info.index()
test = ToDoGUI()
test.mainloop()
This can be done by using enumerate to get the index in the for-loop and then using a lambda as command for the delete button which stores the index. Roughly:
for idx, i in enumerate(a.info):
add_task_label = tk.Label(master=self, bg='red', text=f'{i}')
add_task_label.pack()
delete_btn = tk.Button(self, bg='green', text='Delete', command=lambda idx=idx: self.del_btn(idx))
delete_btn.pack()
...
def del_btn(self, idx):

adding date to tkinter data entry

I'm trying to make a gui of a small project. I want to add the ability to once hitting add_item to add a data entry, it adds a time stamp to it as well. I'm very new to tkinter so any help would be great. I tried something like this:
tk.Button(root, text='add_item', command=lambda :text.insert("end", time.strftime("%d/%m/%Y%H:%M:%S")+'\n'))
b2.pack(side=tkinter.LEFT)
but couldn't get it to work with the rest of the code. I'm assuming it needs a lambda function, not sure how to set it up though.
import tkinter as tk
from datetime import datetime
import time
#1
now = datetime.now()
print ("Current date and time : ")
print (now.strftime("employee-attendance-list-%Y-%m-%d.csv"))
filename = datetime.now().strftime('employee-attendance-list-%Y-%m-%d.csv')
def dt_ins():
e.insert(0, time.asctime())
root = tk.Tk()
root.title("List App")
root.geometry("400x400")
def handler(e):
label= Label(win, text= "You Pressed Enter")
label.pack()
def retrievedata():
''' get data stored '''
global list_data
list_data = []
try:
with open (filename, "r", encoding="utf-8") as file:
for f in file:
listbox.insert(tk.END, f.strip())
list_data.append(f.strip())
print(list_data)
except:
pass
def reload_data():
listbox.delete(0, tk.END)
for d in list_data:
listbox.insert(0, d)
def add_item(event=1):
global list_data
if content.get() != "":
listbox.insert(tk.END, content.get())
list_data.append(content.get())
content.set("")
def delete():
global list_data
listbox.delete(0, tk.END)
list_data = []
def delete_selected():
try:
selected = listbox.get(listbox.curselection())
listbox.delete(listbox.curselection())
list_data.pop(list_data.index(selected))
# reload_data()
# # listbox.selection_clear(0, END)
listbox.selection_set(0)
listbox.activate(0)
listbox.event_generate("<<ListboxSelect>>")
print(listbox.curselection())
except:
pass
def quit():
global root
with open (filename, "w", encoding="utf-8") as file:
for d in list_data:
file.write(d + "\n")
root.destroy()
# LISTBOX
content = tk.StringVar()
entry = tk.Entry(root, textvariable=content)
entry.pack()
button = tk.Button(root, text="Add Item", command=lambda: [add_item(), dt_ins()])
button.pack()
entry.bind("<Return>", add_item)
button_delete = tk.Button(text="Delete", command=delete)
button_delete.pack()
button_delete_selected = tk.Button(text="Delete Selected", command=delete_selected)
button_delete_selected.pack()
listbox = tk.Listbox(root)
listbox.pack()
entry.bind("<Return>,", add_item)
bquit = tk.Button(root, text="Quit and save", command=quit)
bquit.pack()
retrievedata()
root.mainloop()

Using tkinter compare multiple csv and display the matching

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()

Python Deleting Rows Based On One Input

I'm making a program with a GUI using Tkinter.
The program receives a CSV file. And then has functions Add Delete Update
I'm done with the add part, but I could also finish the delete part, but somehow I just want to try out deleting via column. For example, entry is:
2012-1221, Name Lastname,
I want to delete all this entry just by the ID Number 2012-1221
I can't just do it. Here's my code:
from Tkinter import *
import sys
import sys
import os
import operator
import datetime
import csv
import fileinput
root = Tk()
root.title("SCS Club/Guilds/Committee System")
root.grid()
root.geometry("400x450")
root.resizable(width=False, height=False)
files = StringVar()
label = Label(root, text="Clearance and Management", bg="white", fg="black")
label.pack(fill=X)
label1 = Label(root, text="Student Record", bg = "lightgreen", font = "chiller 20 bold").pack()
label2 = Label(root, text ="Enter file name:").pack()
fileName = Entry(root, textvariable=files, relief=GROOVE, bg="lightgreen").pack()
def fileOpen():
def newWindow():
def addData():
idGet = str(idno.get())
nameGet = str(nme.get())
courseGet = str(crse.get())
yearGet = str(yr.get())
fileNameGet = str(files.get())
with open(fileNameGet, 'ab') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar = '|')
completeFields = idGet + ',' + nameGet +','+ courseGet +','+ yearGet
writer.writerow([completeFields])
addEntry.delete(0,"end")
idEntry.delete(0,"end")
crseEntry.delete(0,"end")
newWin = Toplevel()
newWin.geometry("400x200")
newWin.resizable(width=False,height=False)
newWin.title("Add Student")
addId = Label(newWin, text="ID Number").grid(row=1, column=0)
idno = StringVar(None)
idEntry = Entry(newWin, textvariable=idno,bg="lightgreen")
idEntry.grid(row=1, column=1)
addNme = Label(newWin, text="Name").grid(row=2, column=0)
nme = StringVar(None)
addEntry = Entry(newWin, textvariable=nme, text="Name")
addEntry.grid(row=2, column=1)
addCrse = Label(newWin, text="course").grid(row=3, column=0)
crse = StringVar(None)
crseEntry = Entry(newWin, textvariable=crse, text="Course")
crseEntry.grid(row=3, column=1)
addYr = Label(newWin, text="Year").grid(row=4, column=0)
yr = StringVar(None)
yrEntry = Entry(newWin, textvariable=yr, text="Year")
yrEntry.grid(row=4, column=1)
addFinal = Button(newWin, text="ADD", command=addData, relief=GROOVE).grid(row=5, column=1)
def deleteWindow():
def deleteData():
getID = str(idno.get())
fileName = str(files.get())
f = open(fileName,"r")
lines = f.readlines()
f.close()
f = open(fileName,"w")
for line in lines:
if line!=getID+"\n":
f.write(line)
f.close()
idEntry.delete(0,"end")
msg = Label(deleteWin, text="Removed Successfully", font="fixedsys 12 bold").place(x=10,y=50)
deleteWin = Toplevel()
deleteWin.geometry("200x100")
deleteWin.resizable(width=False, height=False)
deleteWin.title("DELETE")
delete_id = Label(deleteWin, text="ID Number ").grid(row=0,column=0)
idno = StringVar(None)
idEntry = Entry(deleteWin, text=idno, bg="lightgreen")
idEntry.grid(row=0,column=1)
deleteFinal = Button(deleteWin, text="REMOVE", command=deleteData, relief=GROOVE).grid(row=4, column=1)
filename = str(files.get())
nfile = open(filename, 'a+')
display = Label(root, text="Opened file successfully", font = "fixedsys 12 bold").place(x=10,y=120)
studentList = Listbox(root, width=45, height=14, bg="lightgreen")
for line in nfile:
studentList.insert(END, line)
studentList.place(x=12, y=200)
nfile.close()
addStud = Button(root, text="Add Student", width = 12, height = 2, command=newWindow, relief=GROOVE).place(x=12,y=150)
deleteStud = Button(root, text="Remove Student", width = 12, height = 2,command=deleteWindow, relief=GROOVE).place(x=115,y=150)
updateStud = Button(root, text="Update", width = 9, height = 2,command=updateWindow, relief=GROOVE).place(x=215, y=150)
addFile = Button(root, text="Open File", width = 12, height = 2, command=fileOpen, relief=GROOVE).pack()
root.mainloop()
root.mainloop()
Please look at my delete part. I can delete an entry but I have to Spell out everything, and for the users it would be a hassle right? I want to make it easier by deleting the entry via ID number only. Any help is appreciated. Thanks!

Pickling dictionary data then loading it doesn't work

I am making a client list and I am using a dictionary and pickle to save and store the clients name and age. Unfortunately my save function overwrites any existing users and then my __init__ function doesn't display the pickled data in the dictionary just the ones I have typed in myself. Also the add function doesn't display the label with the client name on it. Can you please help with the pickle problems because I need an answer fast!
Thanks in advance!
from Tkinter import *
import pickle
root=Tk()
dic={}
class Launch(object):
def __init__(self, root):
root.withdraw()
root=Toplevel(root)
root.title("Choose Client")
self.row=3
for key in dic:
Label(root, text=key).grid(row=row, column=0)
self.row+=1
l3=Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1=Entry(root)
self.e1.grid(row=0, column=1)
l4=Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2=Entry(root)
self.e2.grid(row=1, column=1)
b3=Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client=self.e1.get()
age=self.e2.get()
dic[client]=age
Label(root, text="%s" % (client)).grid(row=self.row)
with open("data", "w") as f:
pickle.dump(dic, f)
def load(self):
dic=pickle.load(open("data", "rb"))
app=Launch(root)
root.mainloop()
The load method is not used at all. The following is modified code to use the load.
from Tkinter import *
import pickle
root=Tk()
dic={}
class Launch(object):
def __init__(self, root):
self.load() # <-- load
root.title("Choose Client")
self.row = 3
for key in dic:
Label(root, text=key).grid(row=self.row, column=0)
self.row += 1
l3=Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1=Entry(root)
self.e1.grid(row=0, column=1)
l4=Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2=Entry(root)
self.e2.grid(row=1, column=1)
b3=Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client=self.e1.get()
age=self.e2.get()
dic[client]=age
Label(root, text=client).grid(row=self.row)
self.row += 1 # <--- increase row count
with open("data", "wb") as f:
pickle.dump(dic, f)
def load(self):
# should be declared, otherwise, will create local variable
global dic
try:
dic = pickle.load(open("data", "rb"))
except IOError: # if file does not exist.
pass
app = Launch(root)
root.mainloop()
Following is another version that use instance variable instead of global variable:
from Tkinter import *
import pickle
class Launch(object):
def __init__(self, root):
self.load() # <-- load
root.title("Choose Client")
self.row = 3
for key in self.dic:
Label(root, text=key).grid(row=self.row, column=0)
self.row += 1
l3 = Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1 = Entry(root)
self.e1.grid(row=0, column=1)
l4 = Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2 = Entry(root)
self.e2.grid(row=1, column=1)
b3 = Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client = self.e1.get()
age = self.e2.get()
self.dic[client] = age
Label(root, text=client).grid(row=self.row)
self.row += 1 # <--- increase row count
with open("data", "wb") as f:
pickle.dump(self.dic, f)
def load(self):
try:
self.dic = pickle.load(open("data", "rb"))
except IOError:
self.dic = {}
root = Tk()
app = Launch(root)
root.mainloop()

Categories