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()
Related
I have a Tkinter Treeview, which I import .csv data into. I then manually assign Not Started Yet To Arrive to the row of columnn Current Status via an .option menu drop down. What is the best way to create a function to filter the treeview and only show rows with Not Started in the Current Status column? I have so far explored options using the following doc. Trying .detach but I dont think this appropriate for my application. https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-Treeview.html
import tkinter as tk
from tkinter import *
import tkinter.ttk as tkrttk
from PIL import Image, ImageFont, ImageTk
import csv
from tkinter import filedialog
root = tk.Tk()
button_1 = Button(root, text="Not Started", command = "SomeFunction")
button_1.place(x=0, y=0, height=50, width=150)
treetime = tkrttk.Treeview(root)
treetime['columns'] = ("Column2", "Column3", "Column4", "Column5",
"Column6", "Column7", "Column8", "Column9", "Column10", "Column11")
column_list = list(treetime ['columns'])
treetime.place(x=0, y=60)
treetime.column("#0", width=0)
treetime.column("Column2", width=80, minwidth=50)
treetime.column("Column3", width=80, minwidth=50)
treetime.column("Column4", width=80, minwidth=50)
treetime.column("Column5", width=80, minwidth=50)
treetime.column("Column6", width=80, minwidth=100)
treetime.column("Column7", width=300, minwidth=100)
treetime.column("Column8", width=200, minwidth=100)
treetime.column("Column9", width=200, minwidth=100)
treetime.column("Column10", width=300, minwidth=100)
treetime.column("Column11", width=200, minwidth=100)
treetime.heading('#0', text="", anchor=tk.W)
treetime.heading('Column2', text="Ro Number", anchor=tk.W)
treetime.heading('Column3', text="Date In", anchor=tk.W)
treetime.heading('Column4', text="Time In", anchor=tk.W)
treetime.heading('Column5', text="Time Out", anchor=tk.W)
treetime.heading('Column6', text="Rego Number", anchor=tk.W)
treetime.heading('Column7', text="Customer Name", anchor=tk.W)
treetime.heading('Column8', text="Vehicle Make", anchor=tk.W)
treetime.heading('Column9', text="Vehicle Model", anchor=tk.W)
treetime.heading('Column10', text="Job Description", anchor=tk.W)
treetime.heading('Column11', text="Current Status", anchor=tk.W)
def select_input_file():
global input_file_path
input_file_path = filedialog.askopenfilename(
filetypes=(("CSV files", "*.csv"),))
with open(input_file_path) as csv_file:
rdr = csv.DictReader(csv_file)
for row in rdr:
RoNumber = row['Ro Number']
DateIn = row['Date In']
TimeIn = row['Time In']
TimeOut = row['Time Out']
RegoNumber = row['Rego Number']
CustomerName = row['Customer Name']
VehicleMake = row['Vehicle Make']
VehicleModel = row['Vehicle Model']
JobDescription = row['Job Description']
CurrentStatus = row['Current Status']
treetime.insert("", 0, values=(RoNumber, DateIn, TimeIn, TimeOut, RegoNumber,
CustomerName, VehicleMake, VehicleModel, JobDescription, CurrentStatus))
StatusList = [
"Not Started",
"Yet to Arrive",
]
Status = StringVar()
Status.set(0)
def set_status(value):
row = treetime.focus()
treetime.set(row, 'Column11', value)
def set_status(value):
row = treetime.focus()
if row:
treetime.set(row, 'Column11', value)
drop=tkrttk.OptionMenu(root, Status, "Select Status", *StatusList, command=set_status)
drop.place(x=1440, y=0, height=50, width=150)
drop=tkrttk.OptionMenu(root, Status, "Select Status", *StatusList, command=set_status)
drop.place(x=1440, y=0, height=50, width=150)
root.mainloop()
I have read through a number of samples and my code seems similar, but when I click on the radio button it does not turn green as expected.
the code expects a csv file with the following line
ref, Lang1, Lang2, Lang3, Lang4
I know the code is executing correctly, with the use of debugging print statements through out the code- many removed to simplify the code
import tkinter as tk
import csv as csv
root = tk.Tk()
Sel_Lang = tk.StringVar()
def radioselect():
global lasthit
temp = int(Sel_Lang.get()) -1
buttonlist[temp].config(bg='green')
buttonlist[temp].grid(row=temp, column=1)
if lasthit != temp:
print('last hit greater then 0')
buttonlist[lasthit].config(bg='white')
buttonlist[lasthit].grid(row=lasthit, column=1)
lasthit = temp
with open('Language.csv') as csvfile:
Langptr = csv.reader(csvfile, delimiter=',')
row1 = next(Langptr) #read the header row
langs = (len(row1))
lang=1
while lang < langs:
##print(row1[lang])
MODES.append((row1[lang], lang))
lang = lang + 1
MODES=[]
lasthit = 0
arraycntr = 0
buttonlist = [0] * len(MODES)
for text, mode in MODES:
''' display for the user to select Language
language choices are taken from the first row in the Language.csv file
'''
buttonlist[arraycntr] = tk.Radiobutton(root, height=2, width=15,
borderwidth=10, text=text, font=("Arial", 24, "bold"), bg='white',
variable=Sel_Lang, value=mode, indicatoron=0)
buttonlist[arraycntr].config(command = lambda :radioselect())
buttonlist[arraycntr].grid(row=mode, column=1)
print('In for loop ', arraycntr, text, mode,
len(MODES),buttonlist[arraycntr])
arraycntr += 1
root.mainloop()
no error messages, but the pressed button does not turn green as expected
You need to add option selectcolor
buttonlist[arraycntr] = tk.Radiobutton(root, height=2, width=15,
borderwidth=10, text=text, font=("Arial", 24, "bold"), bg='white',
variable=Sel_Lang, value=mode, indicatoron=0, selectcolor='green')
I'm new in GUI developing.Here i'hv created two GUI, one for taking photo and another for showing features.so,i'hv used two functions.but i don't know some things.Now i need two kinds of help from you.
1)what is the command for printing float value in GUI(not on console)?
2)How to calculate the value of mean,variance ,s.d. etc from a image and how to pass those values from one function to another function?
import tkinter as tk
from tkinter.filedialog
import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print some features of image e.g. Mean, variance,s.d. Etc.
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
dirPath = " "
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
#this is the image
Photo = Image.open(fileName)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
Okay, I took some more time to look into it.
Concerning the calculation of the values, your previous question did that correct, however the variables needed to be accessible globally. Concerning the displaying of a text, you have to add a tkinter text widget. If you want to add more calculated values, just google for numpy + 'value your want'.
I've taken your code and created a working example, see the code below. Note that I removed some stuff that wasn't neede for the example, so copy the lines you need to your own code. Also check out this reference for the text widget.
Result:
Code:
Note: I created 2 text widgets deliberately, to show 2 ways of implementing multiple texts
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
### create a text widget, place it in window1 and insert the text
width_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
width_txt.grid(column=0, row=0)
width_txt.insert(tk.END, "Width: " + str(width))
height_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
height_txt.grid(column=0, row=1)
height_txt.insert(tk.END, "Height: " + str(height) + "\nMean: " + str(mean))
window1.geometry("650x510")
window1.configure(background="lightgreen")
def openphoto():
### this line makes the variables accessible everywhere
global width,height, mean
import numpy as np
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
photo = Image.open(fileName)
#### calculate values
height = np.size(photo, 0)
width = np.size(photo, 1)
mean = np.mean(photo)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
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!
I am building a chat GUI. On enter-key press, I want the text fields to be shown on the text box as well as be saved in a file. I do not want to use separate button. It is being shown in the text box correctly but not getting saved in the file. Please tell me how can it be done. This is my first time using tkinter.
from Tkinter import *
root = Tk()
frame = Frame(root, width=300, height=1000)
frame.pack(side=BOTTOM)
#username entry
L1 = Label(frame, text="User Name")
L1.pack(side = LEFT)
input_username = StringVar()
input_field1 = Entry(frame, text=input_username, width=10)
input_field1.pack(side=LEFT, fill=X)
#addresee entry
L2 = Label(frame, text="#")
L2.pack(side = LEFT)
input_addresee = StringVar()
input_field2 = Entry(frame, text=input_addresee, width=10)
input_field2.pack(side=LEFT, fill=X)
#user comment entry
L3 = Label(frame, text="Comment")
L3.pack(side = LEFT)
input_usertext = StringVar()
input_field3 = Entry(frame, text=input_usertext, width=100)
input_field3.pack(side=LEFT, fill=X)
#write to a file
def save():
text = input_field1.get() + input_field2.get() + input_field3.get()
with open("test.txt", "w") as f:
f.write(text)
#chat box
chats = Text(root)
chats.pack()
def Enter_pressed(event):
input_get_name = input_field1.get()
print(input_get_name)
chats.insert(INSERT, '%s : ' % input_get_name)
input_username.set('')
input_get_add = input_field2.get()
print(input_get_add)
chats.insert(INSERT, '#%s : ' % input_get_add)
input_addresee.set('')
input_get_comment = input_field3.get()
print(input_get_comment)
chats.insert(INSERT, '%s\n' % input_get_comment)
input_usertext.set('')
save()
frame2 = Frame(root)
L2_1 = Label(frame2, text="All chats")
L2_1.pack(side = TOP)
input_field1.bind(Enter_pressed)
input_field2.bind(Enter_pressed)
input_field3.bind("<Return>", Enter_pressed)
frame2.pack()
root.mainloop()
As you said you are setting the input fields to blank
Here's the solution:
def save(text):
with open("test.txt", "w") as f:
f.write(text)
And when calling save:
save(input_get_name+": "+input_get_add+": "+input_get_comment)