Python Program not recognizing global variables when running [duplicate] - python

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.

Related

How to change sheet name after reading an excel file without using openpyxl? [duplicate]

import pandas as pd
import numpy as np
df = pd.read_excel(r"C:\Users\venkagop\Subbu\promo validation testing\P 02. Promotions-UK C1.xls")
df = df[['Promotions', 'Promotions: AE', 'Promotions: Anaplan ID', 'Promotions: Is Optima Scenario?', 'Promotions: SIDs', 'Set Inactive?', 'Start Date', 'End Date', 'Promo Period', 'Promo Optima Status', 'Change Promo Status']]
df = df[(df['Promo Period'] == 'FY1819')]
df = df[(df['Set Inactive?'] == 0 ) & (df['Promotions: Is Optima Scenario?'] == 1)]
df.dropna(subset=['Promotions: SIDs'], inplace=True)
df['Optima vs Anaplan Promo Status Validation'] = ""
df['Optima vs Anaplan Promo Status Validation'] = np.where(df['Promo Optima Status'] == df['Change Promo Status'], 'True', 'False')
df.to_excel(r"C:\Users\venkagop\Subbu\mytest.xls", index = False)
#after this i want to change sheeet1 name to some other name#
There are 2 ways you can approach this problem.
Approach 1
Save the excel file to the correct worksheet name from the beginning, by using the sheet_name argument.
import pandas as pd
writer = pd.ExcelWriter(r'C:\Users\venkagop\Subbu\mytest.xls')
df.to_excel(writer, sheet_name='MySheetName', index=False)
writer.save()
Approach 2
If Approach 1 is not possible, change the worksheet name at a later stage using openpyxl. The advantage of this method is you remove the cost of converting pandas dataframe to Excel format again.
import openpyxl
file_loc = r'C:\Users\venkagop\Subbu\mytest.xls'
ss = openpyxl.load_workbook(file_loc)
ss_sheet = ss.get_sheet_by_name('Sheet1')
ss_sheet.title = 'MySheetName'
ss.save(file_loc)

Binding one combobox to another combobox in while loop in tkinter

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

_tkinter.TclError: Item 1 already exists with tkinter treeview

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)

Python - application to search excel database column - Using tkinter Pandas

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

for loop to insert things into a tkinter window

I have Tkinter program that has to add a significant amount of data to the window so I tried to write a for loop to take care of it but since I have to use a string variable for the name of the object that Tkinter is running .insert() on the object. I didn't explain it very well here is the method
def fillWindow(self):
global fileDirectory
location = os.path.join(fileDirectory, family + '.txt')
file = open(location, 'r')
ordersDict = {}
for line in file:
(key, value) = line.split(':', 1)
ordersDict[key] = value
for key in ordersDict:
ordersDict[key] = ordersDict[key][:-2]
for item in ordersDict:
if item[0] == '#':
if item[1] == 'o':
name = 'ordered%s' %item[2:]
right here is the problem line because I have the variable that matches the name of the entry object already created but 'name' is actually a string variable so it gives me the error "AttributeError: 'str' object has no attribute 'insert'"
name.insert(0,ordersDict[item])
here is the entire class. It makes a Tkinter window and fills it with a sort of shipping screen so all the entries are for how many orders of a certain thing are needed. I'm also very new so I know that I do things the long way a lot.
class EditShippingWindow(Tkinter.Toplevel):
def __init__(self, student):
Tkinter.Toplevel.__init__(self)
self.title('Orders')
family = student
## Window Filling
ageGroupLabel = Tkinter.Label(self,text='Age Group')
ageGroupLabel.grid(row=0,column=0)
itemColumnLabel = Tkinter.Label(self,text='Item')
itemColumnLabel.grid(row=0, column=1)
costColumnLabel = Tkinter.Label(self,text='Cost')
costColumnLabel.grid(row=0, column=2)
orderedColumnLabel = Tkinter.Label(self,text='Ordered')
orderedColumnLabel.grid(row=0, column=3)
paidColumnLabel = Tkinter.Label(self,text='Paid')
paidColumnLabel.grid(row=0, column=4)
receivedColumnLabel = Tkinter.Label(self,text='Received')
receivedColumnLabel.grid(row=0, column=5)
#Item Filling
column1list = ['T-Shirt (2T):$9.00', 'T-Shirt (3T):$9.00', 'T-Shirt (4T):$9.00',
'Praise Music CD:$10.00', ':', 'Vest L(Size 6):$10.00', 'Vest XL(Size 8):$10.00',
'Hand Book (KJ/NIV):$8.75', 'Handbook Bag:$6.00', 'Memory CD (KJ/NIV):$10.00',
':', 'Vest L(size 10):$10.00', 'Vest XL(Size 12):$10.00', 'Hand Glider (KJ/NIV/NKJ):$10.00',
'Wing Runner (KJ/NIV/NKJ):$10.00', 'Sky Stormer (KJ/NIV/NKJ):$10.00', 'Handbook Bag:$5.00',
'Memory CD (S/H/C):$10.00', 'Hand Glider Freq. Flyer:$8.00', 'Wing Runner Freq. Flyer:$8.00',
'Sky Stormer Handbook:$8.00' , ':', 'Uniform T-Shirt Size (10/12/14):$13.00',
'Uniform T-Shirt Size(10/12/14):$13.00', 'Uniform T-Shirt(Adult S / M / L / XL):$13.00',
'3rd & 4th Gr. Book 1 (KJ / NIV / NKJ):$8.75', '3rd & 4th Gr. Book 2 (KJ / NIV / NKJ):$8.75',
'4th & 5th Gr. Book 1 (KJ / NIV / NKJ):$8.75', '4th & 5th Gr. Book 2 (KJ / NIV / NKJ):$8.75',
'Memory CD 3rd & 4th Gr. Book (1/2):$10.00', 'Drawstring Backpack:$5.50']
column1num = 1
for item in column1list:
num = str(column1num)
(title, price) = item.split(':')
objectName1 = 'column1row' + num
objectName1 = Tkinter.Label(self,text=title)
objectName1.grid(row=column1num, column=1)
objectName2 = 'column1row' + num
objectName2 = Tkinter.Label(self,text=price)
objectName2.grid(row=column1num, column=2)
column1num += 1
#Ordered Paid Recieved Filler
for i in range(32):
if i == 11 or i == 22 or i == 0 or i == 5:
pass
else:
width = 10
# First Column
title1 = 'ordered' + str(i)
self.title1 = Tkinter.Entry(self,width=width)
self.title1.grid(row=i,column=3)
#self.title1.insert(0, title1)
#Second
title2 = 'paid' + str(i)
self.title2 = Tkinter.Entry(self,width=width)
self.title2.grid(row=i,column=4)
#self.title2.insert(0, title2)
#Third
title3 = 'received' + str(i)
self.title3 = Tkinter.Entry(self,width=width)
self.title3.grid(row=i,column=5)
#self.title3.insert(0, title3)
## Methods
def fillWindow(self):
global fileDirectory
location = os.path.join(fileDirectory, family + '.txt')
file = open(location, 'r')
ordersDict = {}
for line in file:
(key, value) = line.split(':', 1)
ordersDict[key] = value
for key in ordersDict:
ordersDict[key] = ordersDict[key][:-2]
for item in ordersDict:
if item[0] == '#':
if item[1] == 'o':
self.name = 'ordered%s' %item[2:]
self.name.insert(0,ordersDict[item])
fillWindow(self)
It looks like you have a conceptual error there: inside this method, the variable "name" does not exist up to the last line on the first listing. Then it is created, and points to an ordinary Python string -- if you are using a "name" variable elsewhere on your class that variable does not exist inside this method.
For an easy fix of your existing code, try calling the variable as "self.name" instead of just name where it is created, and on your last line in this method use:
self.name.insert(0,ordersDict[item]) instead.
The self. prefix will turn your variable into an instance variable, which is shared across methods on the same instance of the class.
On a side note, you don' t need even the dictionary much less three consecutive for loops on this method, just insert the relevant values you extract from "line" in your text variable.

Categories

Resources