How to get value from Entry in Python tkinter? [duplicate] - python

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 3 years ago.
The code I have attached below functions like this: It takes users ID and marks. It goes through an excel sheet and finds that specific ID. Then it will update the second column in that row with his marks.
However, this code gives me an error when I run it. The error comes from .get() function used for getting value of an Entry. I have used .get() function in other projects where it works.
import xlwt
import xlrd
from xlutils.copy import copy
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
rnn = "global"
maar = "global"
def upload():
rn = entry_1.get()
mar = entry_2.get()
rnn = rn
maar = mar
button_1 = Button(root, text = "Upload", command = upload).place(relx = 0.3,rely = 0.2,anchor = NE)
label_1 = Label(root, text = "Enter Reg No here").place(relx = 0.2,rely = 0.05,anchor = E)
entry_1 = Entry(root).place(relx = 0.5,rely = 0.05,anchor = E)
label_2 = Label(root, text = "Enter marks here").place(relx = 0.2,rely = 0.1,anchor = E)
entry_2 = Entry(root).place(relx = 0.5,rely = 0.1,anchor = E)
workbook = xlrd.open_workbook("file.xls")
sheet = workbook.sheet_by_index(0)
rb = xlrd.open_workbook("file.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
for row in range(sheet.nrows):
row_value = sheet.row_values(row)
if row_value[0] == rnn:
w_sheet.write(row,1,maar)
print (row_value)
wb.save("file.xls")
root.mainloop()

This is where you are going wrong:
You are doing:
entry_1 = Entry(root).place(relx = 0.5,rely = 0.05,anchor = E)
In this case, the entry_1 is a NoneType object.
And NoneType object doesn't have any property get(), therefore it throws an error.
What you should do:
First instantiate an Entry widget and then give your widget a position in the window using the widget reference.
entry_1 = Entry(root)
entry_1.place(relx = 0.5,rely = 0.05,anchor = E)
Updated code:
import xlwt
import xlrd
from xlutils.copy import copy
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
rnn = "global"
maar = "global"
def upload():
rn = entry_1.get()
mar = entry_2.get()
rnn = rn
maar = mar
button_1 = Button(root, text = "Upload", command = upload).place(relx = 0.3,rely = 0.2,anchor = NE)
label_1 = Label(root, text = "Enter Reg No here").place(relx = 0.2,rely = 0.05,anchor = E)
# entry widget 1
entry_1 = Entry(root)
entry_1.place(relx = 0.5,rely = 0.05,anchor = E)
label_2 = Label(root, text = "Enter marks here").place(relx = 0.2,rely = 0.1,anchor = E)
# entry widget 2
entry_2 = Entry(root)
entry_2.place(relx = 0.5,rely = 0.1,anchor = E)
workbook = xlrd.open_workbook("file.xls")
sheet = workbook.sheet_by_index(0)
rb = xlrd.open_workbook("file.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
for row in range(sheet.nrows):
row_value = sheet.row_values(row)
if row_value[0] == rnn:
w_sheet.write(row,1,maar)
print (row_value)
wb.save("file.xls")
root.mainloop()
Hope it helps!

Instead of xlrd use pandas for managing excel files.
To create simple excel file:
import pandas as pd
df = (pd.DataFrame({'ID': [10, 11, 12], 'Mark': ['ww','zz','cc']}))
df.to_excel('data.xlsx')
I add some changes in elements positions.
Now you can update data like below:
import pandas as pd
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
def upload():
id = entry_id.get()
mark = entry_mark.get()
# load excel into data frame
df = pd.read_excel('data.xlsx', index_col=0)
# find proper row and replace value
row_match = df[df['ID'] == int(id)]
if row_match.shape[0] > 0:
df.at[row_match.index[0], 'Mark'] = mark
# save updated file
df.to_excel('data.xlsx')
# set button and labels
button = Button(root, text = "Upload", command=upload)
button.grid(column=1, row=4)
label = Label(root, text = "Id")
label.grid(column=0, row=2)
entry_id = Entry(root)
entry_id.grid(column=1, row=2)
label = Label(root, text = "Mark")
label.grid(column=0, row=3)
entry_mark = Entry(root)
entry_mark.grid(column=1, row=3)
root.mainloop()

Related

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

How do I use grid system on entry widget affected by .get()

my code:
import tkinter as tk
from tkinter import *
truth = ""
us = ""
uss = ""
root = Tk()
s = Label(root, text = ".")
s.grid(row = 1, column = 1)
wel = Label(root, text = "whats your email")
wel.grid(row = 1, column = 5)
inp = Entry(root).get()
inp.grid(row = 3, column = 5)
def callback():
us = inp[:inp.index("#")]
uss = inp[inp.index("#")+1:]
truth =us, " is username, and ", uss,"is domain"
print(truth)
sub = Button(root, text = "submit", command = callback)
sub.grid(row = 5, column = 5)
final = Label(root, textvariable = truth)
final.grid(row = 5, column = 6)
root.mainloop()
Then I get an error message:
'str' object has no attribute 'grid'
How do I use grid system on entry widget affected by .get()?

How to delete text from Tkinter?

I want to know how do u delete text inside the Tkinter. The text is circled in red.
My code is as below:
from tkinter import *
from tkinter.ttk import Combobox
import win32com.client
root = Tk()
root.title('PM1 Digital Checklist')
root.geometry("400x400")
def open_excel():
if combo.get() == 'PPM8001':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8001.xlsx")
if combo.get() == 'PPM8002':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8002.xlsx")
if combo.get() == 'PPM8003':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8003.xlsx")
options = ['PPM8001','PPM8002','PPM8003']
v = list(options)
combo = Combobox(root, values = v, width =40)
combo.set("Select which Prime Mover number")
combo.pack()
button = Button(root, text = "Select", command = open_excel).pack()
root.mainloop()
The image is here:
There are 2 things to fix:
use
myLabel = Label(root, text="Prime Mover Number Selected is:")
myLabel.pack()
To actually put a Label instance into a variable
use
myLabel.destroy()
To get rid of it.
Hope that's helpful!

How To Save a key to a dictionary forever?

iam trying to make a phonebook using python and tkinter . I need to add new numbers to my phonebook
by adding elements to the dictionary but i can't access the numbers again after the programme is closed .
from tkinter import*
#defining the submit button
def submit():
global my_dict
new = entry2.get()
new2 = entry3.get()
my_dict.update({new:new2})
#definig the add button
def add():
top = Toplevel(root)
top.configure(background="black")
top.geometry("400x400")
top.title("Add new member")
label6 =Label(top,text="Welcome",bg="black",fg="orange")
label6.place(x=135,y=13)
global entry2
entry2 = Entry(top,width=23)
entry2.place(x=102,y=78)
label7 = Label(top,text="Name",bg="black",fg="orange")
label7.place(x=48,y=78)
global entry3
entry3 = Entry(top,width = 23)
entry3.place(x=108,y=127)
label8 = Label(top,text="phone number",bg ="black",fg="orange")
label8.place(x=0,y=129)
button3 = Button(top,text="Submit",command = submit)
button3.place(x=185,y=200)
button5 = Button(top,text = "close",command = top.quit)
button5.place(x=185,y=300)
#defining the chek button
def check():
person = entry.get()
if person in my_dict:
phone = my_dict.get(person)
print("Found: " + person + " : " + phone)
# Erase the old result by placing a blank label
label0 = Label(root, width=200, bg ="black", fg = "black").place(x=10,y=167)
label5 = Label(root, text = person + " : " + phone, bg ="black", fg = "orange").place(x=10,y=167)
#creating the main window
root = Tk()
global my_dict
my_dict = {"john":'7598769587'}
root.title("vole phone book")
root.geometry("400x400")
root.configure(background="black")
label = Label(root,text="phone book",bg="black",fg="orange",width=13).place(x=133,y=23)
label2 = Label(root,text="Enter here.",bg = "black",fg="orange").place(x=2,y=89)
entry = Entry(root,width = 27)
entry.place(x=89,y=90)
button =Button(root,text="Check",bg="yellow",fg="red",command=check).place(x=190,y=129)
button2=Button(root,text="Add",width=23,command = add).place(x=120,y=300)
root.mainloop()
this is my code,what to do?
Variables in Python are not saved to disk, they only exist in memory (RAM) unless you explicitly save it there yourself.
You can either save to a file directly or, use a database instead.
See Here for using Pickle to do what you want.

python TypeError when using OptionMenu Tkinter [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 6 years ago.
ive currently been trying to build a GUI application in Tkinter that takes user input from an Entry and subsiquently populate a drop down menu. The probelm is that the OptionMenu keeps throwing:
Traceback (most recent call last):
File "C:/Python34/food2GUIree.py", line 70, in <module>
mealOneButton = Button(root, text = "query database", command = GetEntry(mealOneString))
File "C:/Python34/food2GUIree.py", line 68, in GetEntry
meal = OptionMenu(root, '', *getMeal).pack()
TypeError: __init__() missing 1 required positional argument: 'value'
when i replace getMeal in:
def GetEntry(x):
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, '', *getMeal).pack()
with list = [1,2,3,4] or any other list it works fine. why is this?
bellow is the complete program:
from tkinter import *
from tkinter import ttk
import csv
import os
u = "C:\\Users\\luke daniels\\Documents\\fooddata.csv"
"""
Loads csv and compares elements from foodList with current row.
returns a list of rows that match elements in foodList.
"""
def CsvLoadSearch(u, foodList):
results = []
inputfile = open(u)
for row in csv.reader(inputfile):
for food in foodList:
if food in row[0]:
results.append(row[0])
##print(row)
return results
root = Tk()
root.title("MacroCalc")
caloriesAim = StringVar()
protien = StringVar()
fat = StringVar()
carbs = StringVar()
mealOneString = StringVar()
mealTwoString = StringVar()
mealThreeString = StringVar()
mealFourString = StringVar()
mealFiveString = StringVar()
mealSixString = StringVar()
mealOneKeyword = Entry(root, textvariable = mealOneString)
mealTwoKeyword = Entry(root, textvariable = mealTwoString)
mealThreeKeyword = Entry(root, textvariable = mealThreeString)
mealFourKeyword = Entry(root, textvariable = mealFourString)
mealFiveKeyword = Entry(root, textvariable = mealFiveString)
mealSixKeyword = Entry(root, textvariable = mealSixString)
mealLabel = Label(root,text = "meals")
mealLabel.config(font=("Courier", 30))
mealLabel.pack()
mealLone = Label(root,text = "meal one")
mealLtwo = Label(root,text = "meal two")
mealLthree = Label(root,text = "meal three")
mealLfour = Label(root,text = "meal four")
mealLfive = Label(root,text = "meal five")
mealLsix = Label(root,text = "meal six")
caloriesLabel = Label(root,text = "calories needed").pack()
calories = Text(root, height = 1, width = 10).pack()
protienLabel= Label(root,text = "protien ratio").pack()
protien = Text(root, height = 1, width = 4).pack()
carbsLabel = Label(root,text = "carbohydrate ratio").pack()
carbs = Text(root, height = 1, width = 4).pack()
fatsLabel = Label(root,text = "fats ratio").pack()
fats = Text(root, height = 1, width = 4).pack()
displayText = Text(root).pack(side = RIGHT)
def GetEntry(x):
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, '', *getMeal).pack()
mealOneButton = Button(root, text = "query database", command = GetEntry(mealOneString))
mealTwoButton = Button(root, text = "query database", command = GetEntry(mealTwoString))
mealThreeButton = Button(root, text = "query database", command = GetEntry(mealThreeString))
mealFourButton = Button(root, text = "query database", command = GetEntry(mealFourString))
mealFiveButton = Button(root, text = "query database", command = GetEntry(mealFiveString))
mealSixButton = Button(root, text = "query database", command = GetEntry(mealSixString))
mealButtons = [mealOneButton, mealTwoButton, mealThreeButton, mealFourButton, mealFiveButton, mealSixButton]
mealKeywords = [mealOneKeyword, mealTwoKeyword, mealThreeKeyword, mealFourKeyword, mealFiveKeyword, mealSixKeyword]
mealLabels = [mealLone, mealLtwo, mealLthree, mealLfour, mealLfive, mealLsix]
##meals = [mealOne, mealTwo, mealThree, mealFour, mealFive, mealSix]
##packs the drop downs and respective lables
i = 0
while i < len(mealLabels):
mealLabels[i].pack()
mealKeywords[i].pack()
mealButtons[i].pack()
##meal.pack()
i = i + 1
root.mainloop()
throw away lambda function is needed after command when creating the buttons

Categories